Why is a round-trip conversion via a string not safe for a double?

前端 未结 3 1634
一整个雨季
一整个雨季 2020-12-01 03:56

Recently I have had to serialize a double into text, and then get it back. The value seems to not be equivalent:

double d1 = 0.84551240822557006;
string s =          


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 04:42

    Recently, I'm trying to resolve this issue. As pointed out through the code , the double.ToString("R") has following logic:

    1. Try to convert the double to string in precision of 15.
    2. 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.
    3. Otherwise, convert the double to string in precision of 17.

    In this case, double.ToString("R") wrongly chose the result in precision of 15 so the bug happens. There's an official workaround in the MSDN doc:

    In some cases, Double values formatted with the "R" standard numeric format string do not successfully round-trip if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems. To work around this problem, you can format Double values by using the "G17" standard numeric format string. The following example uses the "R" format string with a Double value that does not round-trip successfully, and also uses the "G17" format string to successfully round-trip the original value.

    So unless this issue being resolved, you have to use double.ToString("G17") for round-tripping.

    Update: Now there's a specific issue to track this bug.

提交回复
热议问题