Math.Round Method rounding to nearest even number

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.

Vikram


Share this post   Email it

Feedback

Posted on 9/11/2010 5:10:46 PM

This is good thing to know

Posted on 12/18/2010 3:30:05 PM

Nice thing

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2012 Vikram Lakhotia