Patrick Patrick - 5 months ago 25
C Question

IEEE floating-point number to exact base10 character string


printf('%.9e', value)
always print the exact base10 representation of
is an IEEE single precision floating-point number (C/C++ float)?

Will the same hold for
printf('%.17e', value)
is an IEEE double precision floating-point number (C/C++ double)?

If not, how can I?

It appears that
printf('%.17f', value)
printf('%.17g', value)
will not.


Will printf('%.9e', value) always print the exact base10 representation?

No. Consider 0.5, 0.25, 0.125, 0.0625 .... Each value is one-half the preceding and needs another decimal place for each decremented power of 2.

float, often binary32 can represent values about pow(2,-127) and sub-normals even smaller. It would take 127+ decimal places to represent those exactly. Even counting only significant digits, then number is 89+. Example FLT_MIN on one machine is exactly


FLT_TRUE_MIN, the smallest non-zero sub-normal is 151 digits:


By comparison, FLT_MAX only takes 39 digits.


Rarely are exact decimal representation of float needed. Printing them to FLT_DECIMAL_DIG (typically 9) significant digits is sufficient to uniquely display them. Many systems do not print exact decimal representation beyond a few dozen significant digits.

Vast majority of systems I have used printed float/double exactly to at least DBL_DIG significant digits (typically 15+). Most systems do so at least to DBL_DECIMAL_DIG (typically 17+) significant digits.

Printf width specifier to maintain precision of floating-point value gets into these issues.

printf('%.*e', FLT_DECIMAL_DIG - 1, value) will print a float to enough decimals places to scan it back and get the same value - (round-trip).