Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 235
  • Last Modified:

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
0
paul_skin
Asked:
paul_skin
  • 2
1 Solution
 
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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now