Monday, July 18, 2005

Math.Round in .NET

The .NET 1.1 Framework Math.Round function uses an interesting rounding algorithm called "Bankers Rounding". Basically, this means that the numbers are rounded to the nearest even number. So both 5.3 and 5.6 are rounded to the nearest even number, 6. This is different from the rounding algorithm that we applied in elementary school, which is to round up any number that has a fractional element greater than or equal to .50. I'm not sure why they did the rounding this way, but we have to live with it. I did a sample run of some numbers and saw the following when I used Math.Round():

using Math.Round(numbers[i])
====================
774.10 rounded : 774
774.50 rounded : 774
774.99 rounded : 775
775.10 rounded : 775
775.50 rounded : 776
775.99 rounded : 776
775.15 rounded : 775
775.55 rounded : 776

As you can see, 774.50 was rounded to 774 (the nearest whole even number to 774.50).

Apparently, the string.Format() method actually rounds numbers the normal way, as you can tell from this run:

using string.Format("{0:n0}", numbers[i])
=========================================
774.10 rounded : 774
774.50 rounded : 775
774.99 rounded : 775
775.10 rounded : 775
775.50 rounded : 776
775.99 rounded : 776
775.15 rounded : 775
775.55 rounded : 776

Here, all of the numbers with fractional values less than .50 are rounded down to the nearest whole number, while numbers with fractional values greater than .50 are rounded up to the nearest whole number.

Version 2.0 of the framework will provide the ability to specify the type of rounding algorithm to use with the Math.Round() method.

This page is powered by Blogger. Isn't yours?