Printing double without losing precision

后端 未结 7 1178
一整个雨季
一整个雨季 2020-12-01 03:44

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          


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 04:06

    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__).

提交回复
热议问题