views:

6194

answers:

8

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?

Thanks

+7  A: 

Use std::setprecision:

std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;
Paul Beckingham
Is there some kind of MAX_PRECISION macro or enum or something I can pass to std::setPrecision?
Jason Punyon
std::setprecision(15) for a double (ok or 16), log_10(2**53) ~= 15.9
sixlettervariables
std::setprecision(std::numeric_limits<double>::digits10)
Éric Malenfant
@Éric: coool...
Shog9
A: 

cout is an object that has a bunch of methods you can call to change the precision and formatting of printed stuff.

There's a setprecision(...) operation, but you can also set other things like print width, etc.

Look up cout in your IDE's reference.

Uri
+13  A: 

You can set the precision directly on cout and used the fixed format specifier.

double d = 3.14159265358979;
cout.precision(15);
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::digits10);
cout << "Pi: " << fixed << d << endl;
Bill the Lizard
Nice answer. Lotta good stuff in <limits>!
Shog9
A: 

Most portably...

#include <limits>

using std::numeric_limits;

    ...
    cout.precision(numeric_limits<double>::digits10 + 1);
    cout << d;
I'm curious: why the "+1"?
Éric Malenfant
+1  A: 

Here is what I would use:

std::cout << std::setprecision (numeric_limits<double>::digits10 + 1)
          << 3.14159265358979
          << std::endl;

Basically the limits package has traits for all the build in types.
One of the traits for floating point numbers (float/double/long double) is the digits10 attribute. This defines the accuracy (I forget the exact terminology) of a floating point number in base 10.

See: http://www.cplusplus.com/reference/std/limits/numeric_limits.html
For details about other attributes.

Martin York
A: 

With ostream::precision(int)

cout.precision( numeric_limits<double>::digits10 + 1);
cout << M_PI << ", " << M_E << endl;

will yield

3.141592653589793, 2.718281828459045

Why you have to say "+1" I have no clue, but the extra digit you get out of it is correct.

Jann
A: 

how to accomplish the same task in C ??..

purushottam
A: 
printf("%.12f", M_PI);

%.12f means floating point, with precision of 12 digits.

Maister