This post first appeared on the Forse company blog.
Our project is delivering calculation heavy software used by engineers. We are performing complex numeric operations, and it’s utterly crucial that our software is calculating correctly. Recently, one in our team just encountered that
Math.Round() is behaving differently than what we have expected.
When rounding decimals to integers, we expected
Math.Round() to behave like this:
2.4 -> 2 2.5 -> 3
At least that’s what we learned at school. Well, it turned out that we were wrong. Here is a tiny program that demonstrates this.
This was the outcome:
So, here we see that
2.5 gets rounded to
2 rather than
3. However, for
3.5, it’s exactly how we expected it to be.
To quote from the documentation:
Return Value Type: System.Decimal 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, the even number is returned.[…]
Note the emphasized part of. This behavior is actually intended and by design!
So, in order to get
Math.Round() to behave how we expected it to be, we needed to specify the
MidpointRounding.AwayFromZero like this:
This will give the following outcome:
Which is exactly what we wanted.