Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cout a float number with n decimal places [duplicate]

People also ask

Can you cout a float?

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).

How do you get a float number up to 2 decimal places?

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 %.

How do I get 6 decimal places in C++?

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;