I've noticed that when I call Math.Round and supply it with a decimal value of -0.375 and try to round it to two decimal places, it rounds the value to -0.38. I've always been taught that 5 or greater means to round up which means it should be -0.37. Rounding to -0.37 is how Javascript does this which is how I found this problem to begin with.
Here is some sample code.
decimal negNumber = -0.375m;
var resultToEven = Math.Round(negNumber, 2, MidpointRounding.ToEven);
var resultAwayFromZero = Math.Round(negNumber, 2, MidpointRounding.AwayFromZero);
Console.WriteLine("Original Number: " + negNumber);
Console.WriteLine("ToEven: " + resultToEven);
Console.WriteLine("Away from zero: " + resultAwayFromZero);
And here is what it outputs.
Original Number: -0.375
ToEven: -0.38
Away from zero: -0.38
I am using .NET 4.0.
The default behavior in Math.Round is to use MidpointRounding.ToEven, which rounds "toward the nearest even number".
MSDN describes why this was chosen:
If the digit in the digits position is odd, it is changed to an even digit. Otherwise, it is left unchanged. This behavior follows IEEE Standard 754, section 4. It is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.
Your second call uses AwayFromZero, which explicitly rounds:
toward the nearest number that is away from zero
In your case, -0.38 is "further" away from 0.0 than -0.37.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With