I am taking a C++ class and one of our assignments is to format output for a number. We are suppose run a number first using double and then trying it as a float and formatting those numbers to 3, 4, 5, and 6 decimal positions. The number used is
42.98765. The code for the formatting is (replace double for float is get the double values):
CODE
int numberOne = 32;
float numberTwo = 42.98765f;
cout << "|" << setw(10) << setprecision(3) << fixed << numberTwo << "|" << endl
<< "|" << setw(10) << setprecision(4) << fixed << numberTwo << "|" << endl
<< "|" << setw(10) << setprecision(5) << fixed << numberTwo << "|" << endl
<< "|" << setw(10) << setprecision(6) << fixed << numberTwo << "|" << endl;
I can understand after running it as a double why it would add a 0 for the final number (setprecision(6)) so the answer would be '| 42.987650|'. I can understand that because, if I remember right, double is precise up to 15 decimal places. When I run it as a float, it comes up with '| 42.987652|'. Why does it decide to add a 2 and not a 0. I realize, again, if I remember right, float is precise up to 6 decimal places.
Any explanation of this is greatly appreciated!