Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding doubles - .5 - sprintf

I'm using the following code for rounding to 2dp:

sprintf(temp,"%.2f",coef[i]); //coef[i] returns a double

It successfully rounds 6.666 to 6.67, but it doesn't work properly when rounding 5.555. It returns 5.55, whereas it should (at least in my opinion) return 5.56.

How can I get it to round up when the next digit is 5? i.e. return 5.56.

edit: I now realise that this is happening because when I enter 5.555 with cin it gets saved as 5.554999997.

I'm going to try rounding in two stages- first to 3dp and then to 2dp. any other (more elegant) ideas?

like image 975
Meir Avatar asked Jun 15 '09 06:06

Meir


2 Answers

It seems you have to use math round function for correct rounding.

printf("%.2f %.2f\n", 5.555, round(5.555 * 100.)/100.);

This gives the following output on my machine:

5.55 5.56
like image 120
ypnos Avatar answered Sep 22 '22 17:09

ypnos


The number 5.555 cannot be represented as an exact number in IEEE754. Printing out the constant 5.555 with "%.50f" results in:

5.55499999999999971578290569595992565155029300000000

so it will be rounded down. Try using this instead:

printf ("%.2f\n",x+0.0005);

although you need to be careful of numbers that can be represented exactly, since they'll be rounded up wrongly by this expression.

You need to understand the limitations of floating point representations. If it's important that you get accuracy, you can use (or code) a BCD or other decimal class that doesn't have the shortcoming of IEEE754 representation.

like image 30
paxdiablo Avatar answered Sep 25 '22 17:09

paxdiablo