How to check if float is an integer?

There is some function for the printf function in which you can use% g, which displays the integer 3 if the float is 3.00 and will show 3.01 if it is actually a float, is there any you can do it through some code?

+4
source share
2 answers

There is really no easy answer

Integral values ​​have exact representations in float and double formats. So, if it really is already integrated, you can use:

 f == floor(f) 

However, if your value is the result of a calculation that at some point included some non-zero fractional part, then you will need to worry that you may have something very close to the whole, but which is not really, for sure, the last thing is the same. You probably want to consider this an integral part.

One way to do this:

 fabs(f - round(f)) < 0.000001 

And although we are on this subject, for purists, we should note that int i = f; or double i = f; will round according to the FPU mode, while round (3) will round half the cases from zero.

+8
source

Try the double function modf (double, double *). [Http://www.codecogs.com/reference/computing/c/math.h/modf.php] [1]

0
source

All Articles