Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Round for decimal in C# [duplicate]

Tags:

c#

.net

math

Possible Duplicate:
Why does .NET use banker's rounding as default?

Here is a sample code

decimal num1=390, num2=60, result;
result=num1/num2; // here I get 6.5
result=Math.Round(result,0);

the final value of result should be 7 but, I am getting 6. Why such a behavior?

like image 401
ajay_whiz Avatar asked Nov 26 '25 07:11

ajay_whiz


1 Answers

Check third parameter MidpointRounding.

By default used MidpointRounding.ToEven, so

Math.Round(result,0); // 6.0 
//or
Math.Round(result,0, MidpointRounding.ToEven); // 6.0 

//But:
Math.Round(result,0, MidpointRounding.AwayFromZero); // 7.0 
like image 191
Andrew Orsich Avatar answered Nov 27 '25 21:11

Andrew Orsich



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!