Question

.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)

Was it helpful?

Solution 2

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

OTHER TIPS

Math.Floor(double) seems to be supported, so;

private static double RoundToTwo(double value)
{
    return Math.Floor(100*value + .5)/100;
}

Console.WriteLine(RoundToTwo(1.165));
> 1.17

Console.WriteLine(RoundToTwo(1.16499));
> 1.16

Try

    double number = 1.165;
    string RoundedNumber = number.ToString("f3");

Where 3 is the scale

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top