Float formatting

Hello. I would like to be told how to format the decimals of a float variable.
In C, you just do it like this:
printf("The number is %3.2f",x);
It gives you 3 places for the number before the decimal point and 2 for the decimals (it gives more then 3 if the number is longer). This is useful if the number is for ex 5.123456 and it will print out 5.12. How to do this in C++? I wrote a program in C++, but when I had to format the decimals, I used a C line. That is not the solution though. Thanks for your answer.

Greetings,
Davor
You can use formatting flags(<ios>) or/and manipulators (<iomanip>). It's a small guide:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cout.setf(ios::fixed, ios::floatfield);
// == cout << fixed == %f in printf

cout.setf(ios::scientific, ios::floatfield);
// == cout << scientific == %e in printf

cout.unsetf(ios::floatfield);
// == %g in printf

cout.precision(2)
// == cout << setprecision(2) == %.2 in printf

cout.width(5)
// == cout << setw(5) == %5 in printf
// influences only pn the next outputing value 
Last edited on
Topic archived. No new replies allowed.