0

The following code seems to work fine in .NET 4.7.2, but stops working in .NET core :

(tested with https://dotnetfiddle.net/ )

Console.WriteLine(decimal.ToDouble(10500000000.000000000000m));
Console.WriteLine(Convert.ToDouble(10500000000.000000000000m));
Console.WriteLine((double)10500000000.000000000000m);

Before it correctly returned 10500000000, now it is returning 10499999999.999998

Am I missing something?

Timothy G.
  • 6,335
  • 7
  • 30
  • 46
Thomas
  • 5,603
  • 5
  • 32
  • 48
  • 1
    [This post](https://stackoverflow.com/questions/65266396/why-is-dotnet-core-parsing-doubles-differently-than-net-framework) has a comment linking to a .NET Core 3.0 change https://devblogs.microsoft.com/dotnet/floating-point-parsing-and-formatting-improvements-in-net-core-3-0/ That could probably be why – Timothy G. Dec 09 '22 at 13:31
  • Indeed, parsing 10500000000m works. – Thomas Dec 09 '22 at 13:37
  • 1
    `Before it correctly returned 10500000000` - it didn't though, did it? This code does not return anything, it prints to console. The actual `double` value that is returned by the three conversion methods [was, in fact](https://dotnetfiddle.net/qEjfNz), `10499999999.999998` in .NET 4.7.2 too. – GSerg Dec 09 '22 at 13:37
  • that's a good point. – Thomas Dec 09 '22 at 13:45
  • It seems to be depends on the number of 0 after the dot : This works : Console.WriteLine(decimal.ToDouble(10500000000.00000000000m).ToString("R")); not this : Console.WriteLine(decimal.ToDouble(10500000000.000000000000m).ToString("R")); – Thomas Dec 09 '22 at 13:48
  • yes it does, thank you for the link. – Thomas Dec 09 '22 at 15:13

1 Answers1

0

It looks like .NET Core has a higher precision than .NET 4.7.2 and that's why you have a difference.

You can try to round your double to avoid getting this result.

decimal value = 10500000000.000000000000m;
double rounded = decimal.ToDouble(decimal.Round(value, 0));
Console.WriteLine(rounded); // Output: 10500000000
Timothy G.
  • 6,335
  • 7
  • 30
  • 46