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

Chan picture Chan · Nov 18, 2010 · Viewed 87.9k times · Source

I need help on keeping the precision of a double. If I assign a literal to a double, the actual value was truncated.

int main() {
    double x = 7.40200133400;
    std::cout << x << "\n";
}

For the above code snippet, the output was 7.402
Is there a way to prevent this type of truncation? Or is there a way to calculate exactly how many floating points for a double? For example, number_of_decimal(x) would give 11, since the input is unknown at run-time so I can't use setprecision().


I think I should change my question to: How to convert a double to a string without truncating the floating points. i.e.

#include <iostream>
#include <string>
#include <sstream>

template<typename T>
std::string type_to_string( T data ) {
    std::ostringstream o;
    o << data;
    return o.str();
}

int main() {
    double x = 7.40200;
    std::cout << type_to_string( x ) << "\n";
}

The expected output should be 7.40200 but the actual result was 7.402. So how can I work around this problem? Any idea?

Answer

fredoverflow picture fredoverflow · Nov 18, 2010

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!