How can i see if a float number doesnt have any ",", in other words, if it is an integer.

Printable View

- 01-17-2007Scarvengerfloat
How can i see if a float number doesnt have any ",", in other words, if it is an integer.

- 01-17-2007DesolationCode:
`if(myFloatNumber > (int) myFloatNumber)`

// you have an integer

- 01-17-2007robatinoQuote:

Originally Posted by**Desolation**

Edit: I think there's a fairly small limit on the size of integer which can be represented exactly as a 32-bit IEEE 754 float, since there are only 23 bits for the mantissa.

Edit: 23 bits should translate to being able to represent integers between roughly plus and minus 4 million. A 64-bit IEEE 754 double has 52 bits in the mantissa which provides a much broader range, though to take advantage of it one should cast to a larger than 32-bit integral type - such as long, if a long is 64 bits. Alternatively, instead of the cast you could use floor() or ceil(), defined in <cmath>, to return a floating-point number rounded to the next lower or higher integer, resp., and compare with that. - 01-17-2007Scarvenger
Thank you!

- 01-20-2007robatino
Actually, my suggestions won't work either - see

http://cboard.cprogramming.com/c-programming/87618-how-can-i-test-if-something-integer-not.html

Edit: I may still be right, upon further thought. Follow the above thread for a resolution. - 01-21-2007iMalc
just do the

Code:`if (x == floor(x))`

- 01-21-2007robatinoQuote:

Originally Posted by**iMalc**

Quote:

Originally Posted by**coder8137**

- 01-21-2007iMalc
Oh, so you mean that if you divided 1.0 by 3, and then multiplied that by 3, you would want this to return true? (given the answer would be very very close to 1)

That was not my assumption. I considered this to be an exactness question, such that you could tell if the number stored was a result of having directly assigned an integer previously. In that case this should (and does) return false.

In the non-exact case, you're better of comparing with an epsilon, and looking at the relative error. What you don't do is convert it to an integer type. Doubles can store numbers far above even the largest value a 64-bit number can represent. Of course you can just add more code to just return true if the number falls above that range, since the double can't possibly have any floating point part once it is that large, and you have to check the same for negatives also. But it is probably better to stay within floating point anyway for doing this.