How can i see if a float number doesnt have any ",", in other words, if it is an integer.
How can i see if a float number doesnt have any ",", in other words, if it is an integer.
Code:if(myFloatNumber > (int) myFloatNumber) // you have an integer
That won't work, since the cast truncates toward 0 even if myFloatNumber is negative. You should use "!=" instead of ">", which is more efficient anyway.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.
Last edited by robatino; 01-17-2007 at 09:26 PM.
Thank you!
Actually, my suggestions won't work either - see
How can I test if something is an integer or not?
Edit: I may still be right, upon further thought. Follow the above thread for a resolution.
Last edited by robatino; 01-20-2007 at 11:24 PM.
just do the
thing.Code:if (x == floor(x))
Although as pointed out in the other thread:Originally Posted by iMalc
So if x was derived from an arbitrary calculation, it may no longer be an integer, even if the exact value is.Originally Posted by coder8137
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.