Tuesday, May 31, 2011

Formatting Cout

I just found a neat solution to a common but vexing problem: formatting cout in C++. Turns out its pretty simple. This sample program shows how to enforce two decimal places of precision:


#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
double x = 800000.0/81.0;
double y = 1.2345;

cout << setiosflags(ios::fixed);
cout << setprecision(2);

cout << x << endl;
cout << y << endl;

return 0;
}



>>
9876.54
1.23


The first formatting command enforces a fixed-point output, and the second enforces two decimal places of precision.

A much more complete explanation of options can be found at this blog.

No comments:

Post a Comment