Reputation: 12755
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?
Upvotes: 10
Views: 15162
Reputation: 52357
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
Upvotes: 14
Reputation: 46817
How about this for another possible solution:
printf("%.2f", _nextafter(n, n*2));
The idea is to increase the number away from zero (the n*2 gets the sign right) by the smallest possible amount representable by floating point math.
Eg:
double n=5.555;
printf("%.2f\n", n);
printf("%.2f\n", _nextafter(n, n*2));
printf("%.20f\n", n);
printf("%.20f\n", _nextafter(n, n*2));
With MSVC yields:
5.55
5.56
5.55499999999999970000
5.55500000000000060000
Upvotes: 2
Reputation: 32389
This question is tagged C++, so I'll proceed under that assumption. Note that the C++ streams will round, unlike the C printf family. All you have to do is provide the precision you want and the streams library will round for you. I'm just throwing that out there in case you don't already have a reason not to use streams.
Upvotes: 1
Reputation: 881573
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.
Upvotes: 11
Reputation: 46817
You could also do this (saves multiply/divide):
printf("%.2f\n", coef[i] + 0.00049999);
Upvotes: -2