Integer equivalent to float f
float f=123.456;
can be done using modff() e.g.
float integral, fractional; char str[50], temp[20]; fractional = modff(f, &integral);
Now integral has an integer part (for example, 123.000000) and fractional has a fractional part (for example, 0.456000).
If the floating point number ( f in this case) was negative, both integral and fractional would be negative.
You can do
if(fractional<0) { fractional = -fractional; }
to fix it.
Now,
sprintf(temp, "%g", fractional);
The %g format "0.456" removes trailing zeros, and temp now has "0.456" .
sprintf(str, "%g%s", integral, temp[1]=='.'?temp+2:"");
temp[1]=='.'? performed because if the fractional part was 0 , when printing fractional there would be no decimal point, as it would be 0 , not 0.000000 . If the second character in temp not . , fractional is zero, and we do not need to bother him.
Now in our case str will be "123456" . But this is in the form of a string. We need to convert it to an integer. Use strtol() for this.
long l=strtol(str, NULL, 10); if(l>INT_MAX || errno==ERANGE) { printf("\noverflow"); } else { printf("\n%d", strtol(str, NULL, 10)); }
You can check the return value of strtol() and the errno value (from errno.h . Check if it is ERANGE ) to see if an overflow has occurred.
To find out if the resulting value can be stored in int , first store the value returned by strtol() in long int , and see if it is larger than INT_MAX (it is in limits.h ).
It should be noted that the accuracy of the result will depend on the accuracy with which the floating point number is presented in binary format.