Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my earlier question 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?

like image 989
Jason Punyon Avatar asked Feb 16 '09 18:02

Jason Punyon


People also ask

How do you precise a double value in C++?

By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.

How do you print a full double number?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.


1 Answers

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; 
like image 67
Bill the Lizard Avatar answered Oct 08 '22 05:10

Bill the Lizard