Friday, November 19, 2010

Math.Round rounds numbers, but in which way?!!

I was sure I knew how it rounds fractional parts of number and then I got weird results in some import batch.

So, let's look at the example.
  
Math.Round(1.5) //goes to 2, right?
Math.Round(2.5) //goes to 3, right? Wrong!

Go back to method definition on MSDN and read about method definition and return value once more - here.
  
public static decimal Round(
decimal d
)

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

Okay, let's clarify rule.
  
Math.Round(1.5) //goes to 2
Math.Round(2.5) //goes to 2 !!

Very strange rule if you ask me.

Have a nice day.