Printing double without losing precision

后端 未结 7 1192
一整个雨季
一整个雨季 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:03

    Don't print floating-point values in decimal if you don't want to lose precision. Even if you print enough digits to represent the number exactly, not all implementations have correctly-rounded conversions to/from decimal strings over the entire floating-point range, so you may still lose precision.

    Use hexadecimal floating point instead. In C:

    printf("%a\n", yourNumber);
    

    C++0x provides the hexfloat manipulator for iostreams that does the same thing (on some platforms, using the std::hex modifier has the same result, but this is not a portable assumption).

    Using hex floating point is preferred for several reasons.

    First, the printed value is always exact. No rounding occurs in writing or reading a value formatted in this way. Beyond the accuracy benefits, this means that reading and writing such values can be faster with a well tuned I/O library. They also require fewer digits to represent values exactly.

提交回复
热议问题