Programming Oddity

float value head scratcher

I ran into this at work yesterday. Anyone have any ideas why this might happen? I know it has something to do with the way float values are handled but that doesn’t make me feel any better.

Code Sample

float fVal = 0.7f + 0.25f;

if(fVal == (0.7f + 0.25f))
//this will never be hit
//this will be hit 100% of the time

When looking at the “real” value of fVal it is 0.94999988. That’s all well and good, but obviously it’s not always that. The printed value is 0.95000000.

fVal equals 0.94999988
(0.7f + 0.25f) equals 0.95000000 when in the IF statement.

This is not a teaser. It was the root of a real problem I had to work around yesterday. It took me a while to find it…then D’OH!


Not sure which language you are programming in (C++?), but perhaps the float statement forces a type conversion from the default (eg. to a larger mantissa than the default floating point type) whereas the value to the right of == is stored as the default type and not subjected to the type conversion. So then the difference would come from binary to base 10 conversion (or visa versa) with differing precisions.

I program mostly in the SAS language. In it, there is a FUZZ statement that is used with IF statements to compensate for the fact that such problems can arise. Using FUZZ you set the tolerance for what constitutes floating point equality.