While trying to figure out how to round a float like 1.255 to the nearest hundredth, I found something interesting. I’m using gcc 4.4.5 on Debian 6.
int x = (1.255 * 100) + 0.5; // gives me back 125 instead of 126.
float y = (1.255 * 100) + 0.5; // gives me back 126.000000.
Why is is that when I save to an int I get back 125 and not 126 ? In fedora when I save the above expression to an int I get back 126. Is this a gcc bug in debian ? Any help would be greatly appreciated.
Thanks.
Although this looks like a “typical” floating-point question, it’s more complicated than that.
This one involves a combination of 3 things:
Let’s break this down:
Floating-point literals are of type
doubleby default. Hence1.255is of typedouble.Thus the expression:
is done using type
double.But because binary floating-point can’t represent
1.255exactly, the expression evaluates to:and is of type
double.Since this is less than
126, storing it to an integer will result in125.Storing it to
floatwill round it to the nearestfloat, which results in126.Output: