Have you ever met people looking for magic formulas in C++?
I have, but I did not understand before what were they really looking for.
Today finally I’ve got an idea. For example, if you want to set 2 digits after the decimal point you can use following magic formula in you code:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
and after that all floating point variables will be displayed in the following format:
2.34
5.01
5.00
etc.
example:
#include <iostream>
using namespace std;
int main( )
{
double pi = 3.1415926;
cout << “pi is ” << pi << endl;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << “pi is ” << pi << endl;
cout.precision(7);
cout << “pi is ” << pi << endl;
return 0;
}
jorre
Nov 25, 2010 @ 17:26:44
Thx, this is handy, gr8 job.