5
votes

multiple fixed-point decimal numbers are mapped to the same double value. For example:

double d1 = 132.24;
double d2 =  132.24000000000001;

d1 and d2 have the same binary value.

When converting d1 (or d2, they have the same value) to string using ostream with 14 digits of precision, it is converted to: 132.24000000000001 .

Is there a way/library that supports conversion from double->string, where the string is the fixed-point value with a minimal number of non-zero digits and that is a valid conversion ? i.e. in this case converting d1 to a string will return 132.24000000000000 (shown with 14 digits precision)

1
This precise problem was the subject of the "Dragon4" and "Grisu3" algorithms. It's more-or-less solved, though improvements are still possible.Iwillnotexist Idonotexist
This is how floating point works! Please see Is floating point math broken?Bo Persson
the float/double type of variables cannot represent certain/many values exactly. Your question just happens to hit upon one of those many values.user3629249

1 Answers

2
votes

The library https://github.com/floitschG/double-conversion provides the DoubleToStringConverter::DoubleToAscii method with the SHORTEST option: "SHORTEST: produce the least amount of digits for which the internal identity requirement is still satisfied."

Thanks a lot to iwillnotexist-idonotexist for pointing me to the right direction.