Beware with Math.Round() in C#

Problem 

Recently I found an issue with the Math.Round() function in C# while working on an enhancement project written in Visual Studio 2003. I.e. this function is using the Banker's method. The users of this system didn't like the way figures are getting rounded and they wanted the method used in Excel (Because they are used to Excel Huh?). I.e. Symmetric Arithmetic Rounding method. E.g

Say we want to round 1234.50000 into the nearest integer value. Then Math.Round() returns 1234 whereas MS Excel gives 1235.

I also found a similar issue in SQL Server 2000 some time back. It seems that Microsoft uses contradictory methods of rounding in their products (Visual Studio, SQL Server, Visual Basic, Excel etc.) Tongue Tied

Most of us learnt this banker's method while schooling. But it seems that there are many other ways of rounding. Click here to view all methods of rounding and how you can implement custom rounding procedures.

Solution

Visual Studio 2003 - If we want to use Symmetric Arithmetic Rounding method we have to write our own function instead of using Math.Round(). See below for a working function found in CoderSource.Net.

public static double roundNum(double num, int place)
{

double n;
n = num * Math.Pow(10, place);
n = Math.Sign(n) * Math.Abs(Math.Floor(n + .5));
return n / Math.Pow(10, place);

}

Visual Studio 2005 - This problem is sorted in this version of Visual Studio. We can now select the rounding method in;

System.Math.Round

Rule Of Thumb

Always ask from the users which method of rounding they want during the system requirements gathering stage. This will avoid us being using the default method of rounding in our chosen development language. In this case C#.

References

Wikipedia

Microsoft Help and Support

CoderSource.Net

Published Wednesday, December 26, 2007 2:44 AM by Manjula Perera
Filed under: , ,

Comments

No Comments
Powered by Community Server (Non-Commercial Edition), by Telligent Systems