Monday, November 12, 2012

Banker's Rounding


.NET uses banker's rounding by default, not the common rounding.To override it, specify MidpointRounding.AwayFromZero(aka common rounding) on Math.Round

That is, the presence of 0.5 in a number won't automatically round the number up, rounding up is balanced between odd and even numbers.

When you use Math.Round ​on a number with extra 0.5, the even numbers are rounded down, odd numbers are rounded up.

To illustrate "banker's rounding" (.NET default rounding is banker's rounding. If you want to be explicit about it, specify MidpointRounding.ToEven on Math.Round) :


static void TestBanker()
{
    Console.WriteLine(Math.Round(0.5)); // 0
    Console.WriteLine(Math.Round(1.5)); // 2
    Console.WriteLine(Math.Round(2.5)); // 2
    Console.WriteLine(Math.Round(3.5)); // 4
    Console.WriteLine(Math.Round(4.5)); // 4
    Console.WriteLine(Math.Round(5.5)); // 6
    Console.WriteLine(Math.Round(6.5)); // 6
    Console.WriteLine(Math.Round(7.5)); // 8
    Console.WriteLine(Math.Round(8.5)); // 8
    Console.WriteLine(Math.Round(9.5)); // 10
}


To illustrate "common rounding" (.NET parameter is MidpointRounding.AwayFromZero)


static void TestCommon()
{
    Console.WriteLine(Math.Round(0.5, MidpointRounding.AwayFromZero)); // 1
    Console.WriteLine(Math.Round(1.5, MidpointRounding.AwayFromZero)); // 2
    Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero)); // 3
    Console.WriteLine(Math.Round(3.5, MidpointRounding.AwayFromZero)); // 4
    Console.WriteLine(Math.Round(4.5, MidpointRounding.AwayFromZero)); // 5
    Console.WriteLine(Math.Round(5.5, MidpointRounding.AwayFromZero)); // 6
    Console.WriteLine(Math.Round(6.5, MidpointRounding.AwayFromZero)); // 7
    Console.WriteLine(Math.Round(7.5, MidpointRounding.AwayFromZero)); // 8
    Console.WriteLine(Math.Round(8.5, MidpointRounding.AwayFromZero)); // 9
    Console.WriteLine(Math.Round(9.5, MidpointRounding.AwayFromZero)); // 10
}


Other good explanations:

No comments:

Post a Comment