Bankers Rounding in Math.Round Method

What would be the output of the following program?

 Console.Write(Math.Round(-0.5).ToString() + “~”);
 Console.Write(Math.Round(0.5).ToString()+ “~”);
 Console.Write(Math.Round(1.5).ToString()+ “~”);

 Console.Write(Math.Round(2.5).ToString()+ “~”);

If you think the answer is 0~0~2~3~ then you are wrong. The actual answer is 0~0~2~2~.

And this is no compiler or runtime bug. This is because Dot net framework’s Math class uses Banker’s rounding to round things. According to the banker’s rounding the 0.5 number are rounded to the nearest even number. If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned.

This can lead to some unexpected bugs in financial calculations based on the more well-known Round-Half-Up rounding. To control the type of rounding used by the Round(Decimal) method, call the Math.Round(Decimal, MidpointRounding) overload.


No Comments