Set back default floating point print precision in C++

You can get the precision before you change it, with std::ios_base::precision and then use that to change it back later.

You can see this in action with:

#include <ios>
#include <iostream>
#include <iomanip>

int main (void) {
    double d = 3.141592653589;
    std::streamsize ss = std::cout.precision();
    std::cout << "Initial precision = " << ss << '\n';

    std::cout << "Value = " << d << '\n';

    std::cout.precision (10);
    std::cout << "Longer value = " << d << '\n';

    std::cout.precision (ss);
    std::cout << "Original value = " << d << '\n';

    std::cout << "Longer and original value = "
        << std::setprecision(10) << d << ' '
        << std::setprecision(ss) << d << '\n';

    std::cout << "Original value = " << d << '\n';

    return 0;
}

which outputs:

Initial precision = 6
Value = 3.14159
Longer value = 3.141592654
Original value = 3.14159
Longer and original value = 3.141592654 3.14159
Original value = 3.14159

The code above shows two ways of setting the precision, first by calling std::cout.precision (N) and second by using a stream manipulator std::setprecision(N).


But you need to keep in mind that the precision is for outputting values via streams, it does not directly affect comparisons of the values themselves with code like:

if (val1== val2) ...

In other words, even though the output may be 3.14159, the value itself is still the full 3.141592653590 (subject to normal floating point limitations, of course).

If you want to do that, you’ll need to check if it’s close enough rather than equal, with code such as:

if ((fabs (val1 - val2) < 0.0001) ...

Leave a Comment