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.
The C++ setprecision can also be used to format only the decimal places instead of the whole floating-point or double value. This can be done using the fixed keyword before the setprecision() method.
In order to force C++ to display our floating-point numbers in the scientific format regardless of the size of the number, we use the format specifier scientific inside of cout .
We use the %. 2f format specifier to display values rounded to 2 decimal places.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With