cout prints a floating pointer number with a maximum of 6 decimal places (some compilers may print 5 decimal places) by default (without trailing zeros).
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
setprecision() to Specify Decimal Points We can specify the number of decimal points to print in cout by using the setprecision() function. This function is defined in the iomanip header file, which stands for input/output manipulation.
You need std::fixed
and std::setprecision
:
std::cout << std::fixed << std::setprecision(3) << a;
These require following header:
#include <iomanip>
Try setprecision
:
cout.setf(ios::fixed);
cout << setprecision(3) << a << endl;
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