5

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)

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
Navit F
  • 91
  • 4
  • 7
    This precise problem was the subject of the ["Dragon4" and "Grisu3" algorithms](http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/). It's more-or-less solved, though improvements are still possible. – Iwillnotexist Idonotexist Sep 06 '15 at 13:00
  • 2
    This is how floating point works! Please see [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Bo Persson Sep 06 '15 at 13:46
  • 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 Sep 06 '15 at 18:26

1 Answers1

2

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.

Navit F
  • 91
  • 4