Checking if float is an integer

sidyll picture sidyll · Apr 27, 2011 · Viewed 105.4k times · Source

How can I check if a float variable contains an integer value? So far, I've been using:

float f = 4.5886;
if (f-(int)f == 0)
     printf("yes\n");
else printf("no\n");

But I wonder if there is a better solution, or if this one has any (or many) drawbacks.

Answer

Marc Mutz - mmutz picture Marc Mutz - mmutz · Apr 27, 2011

Apart from the fine answers already given, you can also use ceilf(f) == f or floorf(f) == f. Both expressions return true if f is an integer. They also returnfalse for NaNs (NaNs always compare unequal) and true for ±infinity, and don't have the problem with overflowing the integer type used to hold the truncated result, because floorf()/ceilf() return floats.