How do you print a double to a stream so that when it is read in you don\'t lose precision?
I tried:
std::stringstream ss;
double v = 0.1 * 0.1;
ss
The easiest way (for IEEE 754 double) to guarantee a round-trip conversion is to always use 17 significant digits. But that has the disadvantage of sometimes including unnecessary noise digits (0.1 → "0.10000000000000001").
An approach that's worked for me is to sprintf
the number with 15 digits of precision, then check if atof
gives you back the original value. If it doesn't, try 16 digits. If that doesn't work, use 17.
You might want to try David Gay's algorithm (used in Python 3.1 to implement float.__repr__
).