c++ - printing float, preserving precision -


i writing program prints floating point literals used inside program.

how many digits need print in order preserve precision of original float?

since float has 24 * (log(2) / log(10)) = 7.2247199 decimal digits of precision, initial thought printing 8 digits should enough. if i'm unlucky, 0.2247199 distributed left , right of 7 significant digits, should print 9 decimal digits.

is analysis correct? 9 decimal digits enough cases? printf("%.9g", x);?

is there standard function converts float string minimum number of decimal digits required value, in cases 7 or 8 enough, don't print unnecessary digits?

note: cannot use hexadecimal floating point literals, because standard c++ not support them.

in order guarantee binary->decimal->binary roundtrip recovers original binary value, ieee 754 requires

 original binary value preserved converting decimal , again using:[10]      5 decimal digits binary16     9 decimal digits binary32     17 decimal digits binary64     36 decimal digits binary128  other binary formats required number of decimal digits      1 + ceiling(p*log10(2))   p number of significant bits in binary format, e.g. 24 bits binary32. 

in c, functions can use these conversions snprintf() , strtof/strtod/strtold().

of course, in cases more digits can useful (no, not "noise", depending on implementation of decimal conversion routines such snprintf() ). consider e.g. printing dyadic fractions.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -