Search code examples
c#.net.net-cf-3.5

Rounding to 2 decimal places, without using banker's rounding


.NET and Compact Framework by default use banker's rounding which means that the value: 1,165 will be rounded to: 1,16.

sql server as a opposite rounds it to 1,17 as for me it is the correct behaviour.

Has anyone come across rounding topic and have a workaround for a Compact Framework? (In .net there is an additional parameter which has an influence on the rounding behaviour)


Solution

  • Here is a method you can use instead of decimal.round:

    public static decimal RoundHalfUp(this decimal d, int decimals)
    {
    if (decimals < 0)
    {
        throw new ArgumentException("The decimals must be non-negative", 
            "decimals");
    }
    
    decimal multiplier = (decimal)Math.Pow(10, decimals);
    decimal number = d * multiplier;
    
    if (decimal.Truncate(number) < number)
    {
        number += 0.5m;
    }
    return decimal.Round(number) / multiplier;
    }
    

    Taken from: Why does .NET use banker's rounding as default?

    This question also asks why .Net uses bankers rounding. So I believe it will be a good read for you.

    To answer why

    This bankers algorithm means that results collected will be evenly spread of rounding up/down when the decimal == .5, so really it is just to even out data results.

    Here's another link which describes this by Mr. Skeet