sidyll sidyll - 1 year ago 116
C Question

Checking if float is an integer

How can I check if a

variable contains an integer value? So far, I've been using:

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download