Check if value is a number

mate64 picture mate64 · Feb 17, 2011 · Viewed 22.1k times · Source

How can i simply check if a returned value of type int or uint is a number?

Answer

Taurayi picture Taurayi · Feb 17, 2011

Simple:

if(_myValue is Number)
{
    fire();

}// end if

[UPDATE]

Keep in mind that if _myValue is of type int or uint, then (_myValue is Number) will also equate to true. If you want to know if _myValue is a number that isn't an integer(int) or unsigned integer (uint), in other words a float, then you can simply modify the conditional as follows:

(_myValue is Number && !(_myValue is int) && !(_myValue is uint))

Let's look at an example:

package 
{
    import flash.display.Sprite;
    import flash.events.Event;

    public class Main extends Sprite 
    {

        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            var number1:Object = 1; // int
            var number2:Object = 1.1; // float
            var number3:Object = 0x000000; // uint

            trace(number1 is Number); // true
            trace(number2 is Number); // true
            trace(number3 is Number); // true

            trace(number1 is Number && !(number1 is int) && !(number1 is uint)); // false
            trace(number2 is Number && !(number2 is int) && !(number2 is uint)); // true
            trace(number3 is Number && !(number3 is int) && !(number3 is uint)); // false

        }

    }

}