Alex Rivera | Logout

How can I check if a string is a valid number?

Asked 2008-10-06T19:12:52.413
2048

I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?

Edit
Report

2 Answers

8

Quote:

isNaN(num) // returns true if the variable does NOT contain a valid number

is not entirely true if you need to check for leading/trailing spaces - for example when a certain quantity of digits is required, and you need to get, say, '1111' and not ' 111' or '111 ' for perhaps a PIN input.

Better to use:

var num = /^\d+$/.test(num)
answered 2012-06-01T05:31:14.100
7

parseInt(), but be aware that this function is a bit different in the sense that it for example returns 100 for parseInt("100px").

answered 2008-10-06T19:16:22.737

Your Answer