I have a list of float
values and I want to print them with cout
with 2 decimal places.
For example:
10.900 should be prin
setprecision(n)
applies to the entire number, not the fractional part. You need to use the fixed-point format to make it apply to the fractional part: setiosflags(ios::fixed)
With <iomanip>
, you can use std::fixed and std::setprecision
Here is an example
#include <iostream>
#include <iomanip>
int main()
{
double d = 122.345;
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << d;
}
And you will get output
122.34
Just a minor point; put the following in the header
using namespace std;
then
std::cout << std::fixed << std::setprecision(2) << d;
becomes simplified to
cout << fixed << setprecision(2) << d;
I had this similar problem in a coding competition and this is how I handled it. Setting a precision of 2 to all double values
First adding the header to use setprecision
#include <iomanip>
Then adding the following code in our main
double answer=5.9999;
double answer2=5.0000;
cout<<setprecision(2)<<fixed;
cout <<answer << endl;
cout <<answer2 << endl;
Output:
5.99
5.00
You need to use fixed for writing 5.00 thats why,your output won't come for 5.00.
A short reference video link I'm adding which is helpful
Simplify the accepted answer
Simplified example:
#include <iostream>
#include <iomanip>
int main()
{
double d = 122.345;
std::cout << std::fixed << std::setprecision(2) << d;
}
And you will get output
122.34
Reference:
#include<stdio.h>
int main()
{
double d=15.6464545347;
printf("%0.2lf",d);
}