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.
Apart from the fine answers already given, you can also use
ceilf(f) == forfloorf(f) == f. Both expressions returntrueiffis an integer. They also returnfalsefor NaNs (NaNs always compare unequal) andtruefor ±infinity, and don’t have the problem with overflowing the integer type used to hold the truncated result, becausefloorf()/ceilf()returnfloats.