开发者

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

开发者 https://www.devze.com 2023-01-04 05:02 出处:网络
Is there a way to test a string, such as the one below to see if it\'s an act开发者_开发问答ual number value?

Is there a way to test a string, such as the one below to see if it's an act开发者_开发问答ual 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!


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消