Monday, February 16, 2009

C++ Snippets: Print Precision

How do you print a float or a double to its full precision? By default cout only prints six digits of precision, but you can easily change that.
#include <iostream>
#include <limits>

using namespace std;

typedef numeric_limits<double> dbl;

int main()
double d = 3.14159265358979;
cout << "Pi: " << fixed << d << endl;
return 0;

Use cout's precision function to set the precision to an arbitrary length. Here I used the maximum precision of a double float from the <limits> library. When I print the value, I tell cout to use the specified precision by passing it the fixed specifier.

Compile and run the snippet above and you should see the following output.
$ ./a.out
Pi: 3.141592653589790

No comments: