How to 'cout' the correct number of decimal places of a double value?

Due to the fact the float and double are internally stored in binary, the literal 7.40200133400 actually stands for the number 7.40200133400000037653398976544849574565887451171875

...so how much precision do you really want? :-)

#include <iomanip>    
int main()
{
    double x = 7.40200133400;
    std::cout << std::setprecision(51) << x << "\n";
}

And yes, this program really prints 7.40200133400000037653398976544849574565887451171875!


You must use setiosflags(ios::fixed) and setprecision(x).

For example, cout << setiosflags(ios::fixed) << setprecision(4) << myNumber << endl;

Also, don't forget to #include <iomanip.h>.