1

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

John
  • 1,834
  • 5
  • 32
  • 60

3 Answers3

3

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
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
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

Community
  • 1
  • 1
Philip Gullick
  • 995
  • 7
  • 22
  • Look at these input values: For x = 0.002 I get rounded: 0.010 (xml rounds to 0.000) using the above function ... – John Aug 29 '13 at 08:00
1

Try

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

Where 3 is the scale

Mohammad abumazen
  • 1,286
  • 1
  • 11
  • 24