C# Math.Round (1.785m, 2) not rounded correctly

111 Views Asked by At

I’m experiencing a small issue when I’m trying to round the number 1.785m to two digits. The number can probably not be represented correctly using the decimal data type, since it’s still a floating point number.

I would be excepting the result 1.79m but it’s rounded/present as 1.78m. My question is, how can I achieve a correct result?

My current workaround looks like this:

long l = (long)(1.785m * 1000m);
bool roundUp = l % 10 >= 5;

l = l / 10;

if(roundUp)
    l++;

decimal result = l \ 100;
2

There are 2 best solutions below

0
Mike 'Pomax' Kamermans On

You'll need to explicitly set the rounding mode to MidpointRounding.AwayFromZero:

using System;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      double d, r;
      d = 1.785;
      r = Math.Round(d, 2, MidpointRounding.AwayFromZero);
      Console.WriteLine(r); // 1.79

      d = -1.785;
      r = Math.Round(d, 2, MidpointRounding.AwayFromZero);
      Console.WriteLine(r); // -1.79, not -1.78
    }
  }
}

But as per those code comments: this does exactly what it says on the tin for negative numbers, which will round down rather than up. If you need 0.5 to always round up you'll want Math.ToPositiveInfinity, but depending on your version of .NET, that enum may not be supported.

0
thibsc On

You have to use the third parameter to round as you want (cf. Math.Round):

Math.Round(1.785, 2, MidpointRounding.AwayFromZero); // 1.79