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

37,367

Solution 1

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 ) );

Solution 2

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");
}

Solution 3

Most of the answers on this question have a major flaw in them. If you take Number(null) or Number(undefined) or Number(""), all will return 0 and will evaluate to "is a number". Try something like this instead:

function isANumber( val:* ):Boolean {
    return !(val === null || val === "" || isNaN(val));
}

Solution 4

RegExp path :

function stringIsAValidNumber(s: String) : Boolean {
    return Boolean(s.match(/^[0-9]+.?[0-9]+$/));
}

Solution 5

Here is another way to check if value can be converted to a number:

var ob:Object = {a:'2',b:3,c:'string'};

for( var v:* in ob){
 var nr:Number = ob[v];
 trace(ob[v]+" "+(nr === Number(nr)))
}

this will trace following:

2 true
3 true
string false
Share:
37,367
Bachalo
Author by

Bachalo

Storyteller and constant beginner

Updated on April 05, 2020

Comments

  • Bachalo
    Bachalo over 4 years

    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?