Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to check if a string converted to a number is actually a number in actionscript

Not sure if this makes sense, but I need to check if a server value returned is actually a number. Right now I get ALL number values returned as strings ie '7' instead of 7.

What's the simplest way to check if string values can actually be converted to numbers?

like image 243
Bachalo Avatar asked Aug 06 '09 17:08

Bachalo


2 Answers

The easiest way to do this is to actually convert the string to a Number and test to see if it's NaN. If you look at the Flex API reference, the top-level Number() function says it will return NaN if the string passed to the method cannot be converted to a Number.

Fortunately, Flex (sort of) does this for you, with the isNaN() function. All you need to do is:

var testFlag:Boolean = isNaN( someStringThatMightBeANumber );

If testFlag is false, the string can be converted to a number, otherwise it can't be converted.

Edit

The above will not work if compiling in strict mode. Instead, you will need to first convert to Number and then check for NaN, as follows:

var testFlag:Boolean = isNaN( Number( someStringThatMightBeANumber ) );
like image 144
Dan Avatar answered Sep 20 '22 16:09

Dan


Haven't tested this, but this should work:

if( isNaN(theString) ) {
   trace("it is a string");
} else {
    trace("it is a number");
}

If you are using AS3 and/or strict mode (as pointed out by back2dos), you will need to convert to number first in order for it to compile:

if( isNaN(Number(theString)) ) {
   trace("it is a string");
} else {
    trace("it is a number");
}
like image 35
OneNerd Avatar answered Sep 20 '22 16:09

OneNerd