Mike Moore
Mike Moore

Reputation: 7478

Is there a function to test if a String variable is a number value?

Is there a way to test a string, such as the one below to see if it's an actual number value?

var theStr:String = '05';

I want to differentiate between the string value above and one such as this:

var theStr2:String = 'asdfl';

Thanks!

Upvotes: 6

Views: 5587

Answers (3)

Patrick
Patrick

Reputation: 15717

Yes use isNaN function to test if it the String is a valid Number:

var n:Number=Number(theStr);
if (isNaN(n)){
 trace("not a number");
} else {
 trace("number="+n);
}

Upvotes: 13

FlashJonas
FlashJonas

Reputation: 21

You must cast to Number to get is NaN. If you use int letters can be cast to 0.

Upvotes: 2

Statuswoe
Statuswoe

Reputation: 71

If you are just interested in checking integers you could use the match function as follows, the regex for numbers is more complicated and you would likely be better off following the casting method Patrick provided.

if (s.match(/^\d+$/)){//do something}

Of course if you are going to need to cast it anyway then using isNaN makes perfect sense. Just thought I'd offer an alternative in case you weren't going to cast it.

This code will return true if s contains only digits (no spaces, decimals, letters etc...) and requires there be at least 1 digit.

Upvotes: 0

Related Questions