Checking if a string is numeric

Can anyone tell me how to check if a string is numeric? The string I would be checking would only be 2 characters long.

Many thanks

Paul
paul_skinAsked:
Who is Participating?
 
jhurstCommented:
The length does not matter:

x=parseInt(y);
will set x to the numeric value of the string y, if numeric, if not numeric then x will be set to 'Nan'.
0
 
martinagCommented:
Use isNaN():
isNan(123) will return false
isNan("123") will return false
isNan("123a") will return true

Martin
0
 
martinagCommented:
Actually, jhurst's solution works like this:
parseInt(123) will return 123
parseInt("123") will return 123
parseInt("123a") will return 123
parseInt("") will return NaN
parseInt("a") will return NaN

Martin
0
 
UniDyneCommented:
You need to keep in mind that some implementations (such as Rhino) do not return NaN for parseInt(). In Rhino, parseInt() will still return numbers strings like "123a". isNaN() has worked for me under all JavaScript implementations and appears to be more like what you are looking for.

In Rhino, all of the following statements are true. As you can see, isNaN() is more reliable.

parseInt("123a") == 123
parseInt("234-567") == 234
parseInt("a123") == "NaN"
parseInt("a123") != NaN
isNaN("123a") == true
isNaN("a123") == true
isNaN("234-567") == true
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.