0 Favourites

# How do I test if a variable is an integer

• 8 posts
• I am trying to work out if a variable is in the power of 2 series (e.g. 2, 4, 8, 16, 32 etc). To do this I thought it would be best to take the log of the variable to base 2, if that number was an integer then the variable is within the series. However, I can't find a way to test if the number is an integer or a float/double. Is it possible to test this? If not is there another way to test if the variable is in the sequence?

Develop games in your browser. Powerful, performant & highly capable.

Construct 3 users don't see these ads
• As I'm not a math wiz I usually like to work with predefined lists for stuff like this (I assume there is a better way than what I'm going to suggest but it will probably work). Why not create a dictionary and load the possible variables (2,4,8 etc..) on start of layout and then at runtime when checking just iterate over the list until to see if the number you have matches any in the list. If match return true. depending on how large a number you expect to get you could init the list with a while loop to generate a very large of possible numbers

• briggybros Use the modulus operator. (%)

You can thest if a number is in the power of two like this numberToCheck % 2 = 0

The modulus operator is used to get the remainder of the division. So if you do 4/2 you will get 0 as the remainder so that's how you can check if is in the power of 2, if you try with 3/2 you will get 1 as remainder so it wont pass the check.

Hope that helps, I know my english is not that good.

• Well, that is what I'm using to test. But what I'm trying to achieve may result in the data in the list from being exhausted. I need to do it mathematically so no matter how high the variable is, it will always be able to work it out.

• donelwero That is exactly what I was looking for, thanks

• This is the solution for anyone else interested

• This is the solution for anyone else interested

Just as a matter of precision for someone who is not a math guru:

log(x)/log(2) = log_based_2(x) (log being a log based on any positive number)

so of course log(x)%log(2) ---> If 0, then the log based 2 of x is an integer, and so x is a power of 2

I'm not sure of the actual precision of the value of log(2) is stored, so keep that in mind too

• 8 posts