Wednesday, October 31, 2007

MidpointRounding Enumeration?

I learned something new yesterday, and man do I love learning new things. While evaluating how a piece of our system was behaving a discussion of the Decimal.Round method came up. The code we were evaluating was not something I wrote, but it is something a co-worker and I inherited.

All of the code which we have in this portion of our system uses the overload which takes the decimal to round and an integer describing how many decimal places to round that decimal to. But what is the algorithm that is used to perform this rounding? It's a question I had honestly never asked. I think this is a case where I just made an assumption, and you know what they say about assumptions.

My co-worker introduced me to the System.MidpointRounding enumeration. It turns out that .NET lets you specify how you want the midpoint rounded. This is the case where I always assumed it rounded up. It turns out that is one of the values (AwayFromZero), but there is also another option (ToEven). It also turned out, upon further investigation that ToEven is used by default. I have not verified that Math.Round works in the same manner, but I would assume it would (I know there goes that word again).

ToEven means that when the decimal place being rounded is half way between both options it rounds the digit to the closest even value. For example if you were rounding .215 to 2 decimal places the output would be .22, but if you were rounding .245 to 2 decimal places the output would be .24.

I believe this is to try to minimize the impact of rounding on the average. If you are dealing with a large set of numbers you should receive a relatively even split of numbers which would be rounded up as well as an even split of numbers which would be rounded down resulting in a net effect of zero. This rounding business makes a lot of sense to me now.

--John Chapman

No comments:

Blogger Syntax Highliter