Is there a function to check if a String variable is numeric?

Is there a way to check a string like the one below to see if this value is valid?

var theStr:String = '05'; 

I want to distinguish between the string value above and one such:

 var theStr2:String = 'asdfl'; 

Thanks!

+6
types actionscript-3
source share
3 answers

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

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

You must specify Number to get the NaN value. If you use int , letters can be added to 0 .

+2
source share

If you're just interested in checking for integers, you can use the match function as follows, the regular expression for numbers is more complex, and you probably would be better off following the casting method provided by Patrick.

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

Of course, if you still need to drop it, then using isNaN makes sense. Just thought that I would suggest an alternative if you are not going to give it up.

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

0
source share

All Articles