question about setprecision

Sep 8, 2008 at 3:12am
Hello,
I have this program where I have to do some calculations with data read from a text file with different number formats. For example the file may consists of:
9.09090901
18.1818178
27.2345891
8.9090090
100.99991
After doing such calculations the final result should be one decimal place. For Example, if I have 9.09090901 I want it to be printed as 9.1. However, I have this working with setprecision(2) but if the number in the file is 18.181878 it retrns 18, which is incorrect, I need it to return 18.2. With this is mind, is there any way all numbers are rounded one decimal place.By any chance is there anyone can tell me how to do this or give some advice.Any help will be greatly appreciated.
Sep 8, 2008 at 4:48am
Sep 12, 2008 at 2:58am
Couldn't you use some logic such as ?
If result - int(result) >=0.5 ceil else floor
Sep 12, 2008 at 3:09am
He doesn't want to truncate. He wants to round.
Sep 12, 2008 at 7:22am
my book says that ceil and floor rounds but ooops ....only to the nearest integer and must deal with a floating point number. i guess i need to read your references also!
Sep 12, 2008 at 11:57am
So another way to round to exactly one decimal place is first to multiply the answer by 10, then round to nearest integer, then divide by 10. I'm not going to speak of the accuracy of the result due to floating point roundoff error though.
Sep 13, 2008 at 7:17am
You can easily do that by using the manipulators fixed (to output your floating point in a fixed decimal format) and showpoint (to force the output to show the decimal point and trailing zeros when the decimal numbers are zero).
Manupulator fixed used with a setprecision of 1 will force all your numbers to be displayed with one decimal place and with showpoint even your 5th number will round up to 101.0


Just do:
cout << fixed << showpoint << setprecision(1);
before outputting your numbers.

Good luck!
Topic archived. No new replies allowed.