Setting precision?

• 01-23-2006
markucd
Setting precision?
How can I set the number of decimal places when writing to an ofstream? I want to always write 2 decimal places, even if they are both zero.
Thanks
• 01-23-2006
markucd
In C I have done something like the following:

Code:

`fprintf(parout, "-weight=%2.f", weight);`
This will print out weight with 2 decimal places, even if they are both zero. Is there a way to do this in C++?
Thanks
• 01-23-2006
jlf029
use setprecision(2) with cout and include <iomanip>
eg

int x = 2.143234234;
cout << setprecision(2) << x << endl;
• 01-23-2006
markucd
Doesnt seem to work!
The setprecision function only seems to work if the positions are non zero. Is there some other way? Say I have weight = 10, and I want it to be printed as 10.00. Is there a way to do this?
Thanks

The set precision function takes a value n, and this is the maximum number of decimal places, but it doesnt necessarily use them all.
• 01-23-2006
ZuK
Code:

```double x = 2.143234234; cout << fixed << setprecision(2) << x << endl;```
Kurt
• 01-23-2006
markucd
Thanks!
That works