Search

Mar 8, 2013

Understand the behavior of .NET function Math.Round

Hello All,

Recently I faced wired issue with Math.Round function. What is assumption for Math.Round function is “Rounds a double-precision floating-point value to the nearest integral value”

Lets examine this case. We are trying to Round 10.5 and 11.5

image

We are expecting result as 11 and 12. Let’s see the output

image

Unexpected!!! Does this means Math.Round having bug? Well the obvious answer is No. There is no bug in Math.Round function. Basically we are not using Math.Round function properly Smile

Let’s check what documentation say about Math.Round function.

image

The document says, it will return the nearest EVEN number is returns. This is a reason why we got 10 instead of 11.

This is default behavior of Math.Round to return nearest even number, however we can change the behavior to get out expected result. There are few overloads provided by framework, we can use one which have control to return nearest even or odd which always be larger, in our case we always need large one. So lets use overload function of Math.Round

image

We are mentioning to give us a number which is away from Zero mean bigger one. This will give output as we are expecting.

image 

There we go. So best practice to use Math.Round is always call overloads which is taking mode as an argument. There is two option for MidPointRounding enum, one is AwayFromZero and another is ToEven

I am sure lots of people is going to change their code after reading this blog post Smile

3 comments:

Rajesh Domadia said...

Nice article

Anonymous said...

better use math.ceiling instead of math.round()

Anonymous said...

Nice One Imran