Meir Meir - 5 months ago 26
C++ Question

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?

Answer Source

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