-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
Extract this issue from https://github.com/dotnet/coreclr/issues/10651#issuecomment-315667429
Generally speaking, double.ToString("R") tries to:
- Convert the double to string in 15 digits precision.
- Convert the string back to double and compare to the original double. If they are the same, we return the converted string whose precision is 15.
- Otherwise, convert the double to string in 17 digits precision.
This introduced a bug and also listed as a known issue on MSDN (See "Notes to Callers"):
https://stackoverflow.com/questions/24299692/why-is-a-round-trip-conversion-via-a-string-not-safe-for-a-double
https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
To reproduce this issue, simplely try following code:
using System;
namespace lab
{
class Program
{
static void Main(string[] args)
{
double d1 = 0.84551240822557006;
string s = d1.ToString("R");
double d2 = double.Parse(s);
Console.WriteLine(d1 == d2);
}
}
}The output is False which we expect True. The reason is d1.ToString("R") wrongly chose the result in precision of 15, which is 0.84551240822557. If we choose result in precision of 17, which is 0.84551240822557006, we can convert it back to double accurately.
The proposal is just convert the double to string in 17 digits precision directly. We can give it a try but it may be a breaking change with compat issue as @jkotas said here: https://github.com/dotnet/coreclr/issues/10651#issuecomment-315839827