Joe Woods Joe Woods - 7 months ago 34
C Question

Check if input is float or not in C?

I am trying to create a code which checks if user input is float or not. This is what I have:

while (ceil(var1) == var1 || ceil(var2) == var2) {
printf("Not float \n");
printf("enter float: ");
scanf("%f,%f", var1, var2);

var1 = *num1;
var2 = *num2;

This works a little, but if I enter something like:
it will not accept this as a float.


It appears that what you are trying to determine is whether a floating point variable has a fractional part or not (or whether the float input can be represented exactly as an integer perhaps). That is not the same as whether the

input is float or not

which really makes no sense, a float variable is always float.

Comparing floating point values for equality is always going to be problematic. You generally have to test the difference between the two values is less than some arbitrarily small but representable and acceptable error limit. For example:

fabs(ceil(var1) - var1) < FLT_EPSILON

You might try using modf(), but it may have the same issue. double intpart ; double fractpart = modf( var1, &intpart ) ; if( fabs( fractpart ) < FLT_EPSILON ) { // no fractional part }

Note that the C math library is defined for double rather then float. In many cases the implicit conversions are safe, but not for passing the pointer prameter for modf().