How to cout a float number with n decimal places [

2019-01-09 14:37发布

问题:

Possible Duplicate:
How do I print a double value with full precision using cout?

float a = 175.;
   cout << a;

If I run the previous code I'll get just 175, how can I cout the number with (for example) 3 decimal places even they were zeros .. How can I print "175.000" ?!

回答1:

You need std::fixed and std::setprecision:

 std::cout << std::fixed << std::setprecision(3) << a;

These require following header:

#include <iomanip>


回答2:

Try setprecision:

cout.setf(ios::fixed);
cout << setprecision(3) << a << endl;