How do I print a double value with full precision using cout?


Question

So I've gotten the answer to my last question (I don't know why I didn't think of that). I was printing a double using cout that got rounded when I wasn't expecting it. How can I make cout print a double using full precision?

1
301
5/23/2017 12:10:41 PM

Accepted Answer

You can set the precision directly on std::cout and use the std::fixed format specifier.

double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;

You can #include <limits> to get the maximum precision of a float or double.

#include <limits>

typedef std::numeric_limits< double > dbl;

double d = 3.14159265358979;
cout.precision(dbl::max_digits10);
cout << "Pi: " << d << endl;
355
3/4/2019 6:51:31 PM

Use std::setprecision:

std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon