Reputation: 5271
When cout-ing a number with floating points, i.e. 31.14159, how can I set cout to use the setprecision(4) on the floating point:
cout <<setprecision(4)<< 31.14159<<endl; // returns 31.14
As-is, it considers the whole number with its decimal digits, and outputs: 31.14. However, I want to get: 31.1416.
Upvotes: 5
Views: 6737
Reputation: 2269
std::fixed says that there will be a fixed number of decimal digits after the decimal point.
std::cout << std::setprecision(4) << std::fixed << 31.14159;
- this will print 31.1416
Upvotes: 5
Reputation: 7006
You can use std::fixed
std::cout << std::fixed << std::setprecision(4) << 31.14159 << endl ;
and you will get output as 31.1416
When you add std::fixed
, the std::setprecision(4)
will take effect on the decimal part, and thus you will get 4
values after the decimal point.
A std::setprecision()
will take effect on the entire number. But when you add a std::fixed
along with it, the std::setprecision()
will effect only the decimal part of the number.
Upvotes: 1