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.

1 comment:

Unknown said...

Well, .net (at least version 2) can be very surprising.
I've faced with issue where decimal.Parse("1234.56") depending on your regional settings can simply ignore dot and produce 123456 instead of 1234.56, if e.g. comma "," is decimal separator in your reg. sett. OK, it doesn't like dot it is not by reg. sett. but... why ignore it??? Throw format exception or any appropriate... From my point of view this is subtle behavior which can lead to unexpected results.

Workaround is easy but again... why to ignore dot?!?!? :) :) :)