Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Round double .5

Let say:

Math.Round(2.5) //2.0
Math.Round(-2.5) //-2.0
Math.Round(2.5,MidpointRounding.ToEven) // 2.0
Math.Round(2.5,MidpointRounding.AwayFromZero) //3.0

Question: if I change the number with -77777777.5 why the result is -77777778.0 not -77777777.0

Math.Round(-77777777.5) // -77777778.0
Math.Round(-77777777.5,MidpointRounding.AwayFromZero) // -77777778.0
Math.Round(-77777777.5,MidpointRounding.ToEven) // -77777778.0
like image 728
Husnan Avatar asked Jul 16 '26 04:07

Husnan


1 Answers

The default MidPointRounding mode is ToEven. In this mode, as explained by the documentation (where a is the input value),

The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned.

-77777777.5 has two nearest integers -77777777 and -77777778 but the latter is the even one so that is the one that is returned.

In the AwayFromZero mode, -77777778 is clearly further from zero than -77777777.

like image 82
Daniel Renshaw Avatar answered Jul 19 '26 02:07

Daniel Renshaw



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!