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:
Your second call uses AwayFromZero, which explicitly rounds:
In your case, -0.38 is “further” away from 0.0 than -0.37.