printing float, preserving precision
c, c++, floating-accuracy, floating-point, string
Solution
In order to guarantee that a binary->decimal->binary roundtrip recovers the original binary value, IEEE 754 requires
The original binary value will be preserved by converting to decimal and back again using:[10]
5 decimal digits for binary16
9 decimal digits for binary32
17 decimal digits for binary64
36 decimal digits for binary128
For other binary formats the required number of decimal digits is
1 + ceiling(p*log10(2))
where p is the number of significant bits in the binary format, e.g. 24 bits for binary32.
In C, the functions you can use for these conversions are snprintf() and strtof/strtod/strtold().
Of course, in some cases even more digits can be useful (no, they are not always "noise", depending on the implementation of the decimal conversion routines such as snprintf() ). Consider e.g. printing dyadic fractions.
Problem
I am writing a program that prints floating point literals to be used inside another program. How many digits do I need to print in order to preserve the precision of the original float? Since a float has `24 * (log(2) / log(10)) = 7.2247199` decimal digits of precision, my initial thought was that printing 8 digits should be enough. But if I'm unlucky, those `0.2247199` get distributed to the left and to the right of the 7 significant digits, so I should probably print 9 decimal digits. Is my analysis correct? Is 9 decimal digits enough for all cases? Like `printf("%.9g", x);`? Is there a standard function that converts a float to a string with the minimum number of decimal digits required for that value, in the cases where 7 or 8 are enough, so I don't print unnecessary digits? Note: I cannot use hexadecimal floating point literals, because standard C++ does not support them.