A Flash Developer Resource Site

# Thread: Test for negative or positive numbers

1. ## Test for negative or positive numbers

Is there a way to test if a number is negative or positive.
I have some clips that position themselves on and off the stage. IF one moves in the other moves out the same direction the other is moving in. This also works the same in reverse. I'm trying to do this by checking the current clips position and see if its a negative or positive number. If its a positive then I can move it onto the stage and move the other off in the same direction.

Maybe there is another way of doing this but I thought if I could check its value and see if its negative or positive it would be a start.

2. See if it's less than 0?

3. Although 5tons solution is probably the easiest, there is another possibility, which sometimes becomes handy, which is using uint as datatype. Any negative number is subtracted from 4294967296. So this is also possible:

var a:int = -10;
var m:uint = uint(a);
if(a == m)
{
trace("yes");
}
else
{
trace("no");
}

4. Oh, well if we're going exotic, and we know the number is an int, then we can take advantage of the way ints are stored. ints and uints are stored in 32 bits. Negative ints are stored in a form called 2's-complement, which means that all the bits before the actual value will be 1 for negative numbers. So we can simply test whether the first bit is 1 or 0.
Code:
```var firstBit:uint = 1 << 31
if (myInt & firstBit){
//negative
}else{
//positive.
}```
This won't work if the number to compare is a Number, which is stored differently. Or it might work, but be slower because of inherent type conversions.

This sort of optimization is completely over-the-top unnecessary unless you're trying to shave off microseconds in a tight loop that is called thousands of times. And the vagaries of the compiler and minor considerations mean that it might not be faster at all in the first place.

My advice is to write your code so that it makes sense to you when you read it again after a week.

5. Thanks to you all for these solutions.

6. Originally Posted by cancerinform
Although 5tons solution is probably the easiest...
As I said..., but occasionally there is an application for it

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 » Home » Movies » Tutorials » Submissions » Board » Links » Reviews » Feedback » Gallery » Fonts » The Lounge » Sound Loops » Sound FX » About FK » Sitemap