float variable won't print desired number of digits

I would like the output to print 4.0.
When the program runs it prints 4.
I've tried changing setprecision and changing float type to double, but no difference.

What am I missing here?

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <iomanip>

using namespace std;

float x = 4.0;

int main()
{cout << "Float is " << setprecision(2) << x <<endl;
return 0;
}
Try also using std::fixed.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <iomanip>

using namespace std;

float x = 4.0;

int main()
{
    cout << "Float is " << setprecision(1) << std::fixed << x <<endl;
    return 0;
}


http://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout
Last edited on
You probably want to use std::fixed.

 
cout << "Float is " << fixed << setprecision(1) << x << endl;

http://www.cplusplus.com/reference/ios/fixed/
Topic archived. No new replies allowed.