How to use setprecision in cpp for floating point only
With floating point number disabled, i.e. 31.14159, how can I set cout to use setprecision (4) on floating point:
cout <<setprecision(4)<< 31.14159<<endl; // returns 31.14
As-is, it considers the whole number with decimal digits and prints: 31.14. However, I want to get: 31.1416.
std :: fixed says 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 the result as 31.1416
When you add std::fixed
, std::setprecision(4)
will act on the decimal part and you will get the values 4
after the decimal point.
A std::setprecision()
will take effect for the entire number. But when you add std::fixed
along with it, it std::setprecision()
will only use the decimal part of the number.