Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Round rounds me

Tags:

c#

.net

I understand if .NET rounds 2.5 to 2 using banker's rounding. But, how this could be:

decimal point;
point =51 * 70 / 100;    
Math.Round(point,0, MidPointRounding.AwayFromZero);

rounds to 35?

How can I make all .5's round to upper integer even if it's odd?

like image 631
Mehmet AVSAR Avatar asked Aug 25 '26 08:08

Mehmet AVSAR


2 Answers

This second line in your snippet already gives you an integer result.

51, 70, 100 are of type int, therefore the operators for integer multiplication and division are chosen. The result of an integer multiplication or division is always of type integer again, and possible decimal places are truncated when dividing using / on integers.

The statement point = 51 * 70 / 100; is equivalent to

int tmp = 51 * 70;         // result is 3570
tmp = tmp / 100;           // result is 35 (!!!)
point = (decimal)tmp;      // point is 35m;

The solution is to change your code so that it uses decimal arithmetic:

point = 51m * 70m / 100m;  // point is 35.7m

Actually it is sufficient that one of the operands is of type decimal. This can either be achieved by using the suffix m (for monetary) or by using a type cast. The following sample will also give the desired result:

point = (decimal)51 * 70 / 100;
like image 138
Dirk Vollmar Avatar answered Aug 27 '26 23:08

Dirk Vollmar


You are doing integer division. Try this instead:

decimal point = 51m * 70m / 100m;
like image 35
Darin Dimitrov Avatar answered Aug 27 '26 22:08

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!