11 Vote

JavaScript: Is string a number?

Question by Interest | 2012-07-02 at 21:55

I want to test using a JavaScript script, whether a given string is a number or not. Is there a good way to do it or do I have to check it with a regular expression?

1Best Answer1 Vote

Just use the function isNaN(), which is standing for "is Not a Number". The function accepts a string and returns true if the string is not a number and false if the string is a number.

Here is a small example:

alert(isNaN("123")); //false
alert(isNaN("abc")); //true
alert(isNaN("1.0")); //false
alert(isNaN("1,0")); //true

"123" is a number, so "is Not a Number" is false. "abc" is not a number, therefore, the result is true.

With "1.0" and "1,0", you have to know, that in JavaScript, numbers are separated with a point instead of a comma. So, "1,0" is no number and in contrast, "1.0" is a number.
Last update on 2020-09-03 | Created on 2012-07-02

ReplyPositive Negative

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.