Making a float display no more than 2 decimal places

Hey guys. Right now I'm trying to figure out how to display a float where it won't show more than two decimals but it also won't show two if it doesn't have to.

For example, this is how I would like it to work.

1
2
3
4
5
6
    float Moses = 3.0f;
    cout << Moses; // Displays 3
    float Joshua = 40.3f
    cout << Joshua; // Displays 40.3
    float Jericho = 7.769324;
    cout << Jericho; // Displays 7.77. 


There are no restrictions in this assignment. Any suggestions appreciated.
There is a problem with that.

For example, number 4.3 is not representable in floating point format:
1
2
3
4
std::cout.setf(std::ios::fixed);
std::cout.precision(6);
float Joshua = 40.3f;
std::cout << Joshua << '\n';
40.299999
Therefore that 0 is meaningful and cannot be omitted. If you request it to print 2 decimal digits, it will print trailing 0, to denote that error is less than 0.5 ULP:
0.3 — actual value is between 0.25 and 0.35
0.30 — actual value is between 0.295 and 0.305

See how that extra digit changes precision?

If you still want to cut away trailing zeroes, print number to string, and cut trailing zeroes manually.
Topic archived. No new replies allowed.