开发者

Math.Round rounds me

开发者 https://www.devze.com 2023-01-23 01:36 出处:网络
I understand if .NET rounds 2.5 to 2 using banker\'s rounding. But, how this could be: decimal point; point =51 * 70 / 100;

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开发者_如何学Go integer even if it's odd?


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;


You are doing integer division. Try this instead:

decimal point = 51m * 70m / 100m;
0

精彩评论

暂无评论...
验证码 换一张
取 消