Keep in mind that most of the methods here are valid, assuming that rounding error due to previous calculations is not a factor. For example, you can use roundf , for example:
float z = 1.0f; if (roundf(z) == z) { printf("integer\n"); } else { printf("fraction\n"); }
The problem with this and other similar methods (such as ceilf , casting to long , etc.) of ceilf is that although they work fine for integer constants, they will fail if that number is the result of the calculation, rounding error rounding. For example:
float z = powf(powf(3.0f, 0.05f), 20.0f); if (roundf(z) == z) { printf("integer\n"); } else { printf("fraction\n"); }
It prints a "fraction", although (3 1/20 ) 20 should be 3, because the actual calculation result was 2.9999992847442626953125.
Any similar method, be it fmodf or something else, obeys this. In applications that perform complex or round-robin calculations, usually what you want to do is define a certain “tolerance” value for what constitutes an “integer” (this applies to general floating point comparisons in general). We often call this tolerance epsilon. For example, let's say that we skip the computer to +/- 0.00001 rounding errors. Then, if we test z , we can choose epsilon 0,00001 and do:
if (fabsf(roundf(z) - z) <= 0.00001f) { printf("integer\n"); } else { printf("fraction\n"); }
You really don't want to use ceilf here, because for example ceilf(1.0000001) is 2 not 1, and ceilf(-1.99999999) is -1 not -2.
You can use rintf instead of roundf if you want.
Select a tolerance value suitable for your application (and yes, sometimes a zero tolerance is appropriate). For more information, check out this article on comparing floating point numbers .