Check if a String can be Converted to a Number in JavaScript

To check if a string can be converted to a number or not in JavaScript, you can use the built-in method isNaN(). The method isNaN() takes a single parameter and checks if it can be converted to a number or not.

It returns a boolean false if the passed value can be converted to a number, otherwise, it returns true.

Let’s take an example and understand it:

//  true

// false

In the above example, we first passed the string “abc” to the isNaN() method. As the string “abc” can not be converted to a valid number, therefore it returns true.

And then we passed the string “123”, which can be converted to a valid number 123, therefore, the method isNaN() returns false.

Let’s have a look at a few more examples to understand it deeply:

console.log(isNaN("ab15"));    // true
console.log(Number("ab15"));   // NaN

console.log(isNaN("12.54"));   // false
console.log(Number("12.54"));  // 12.54

console.log(isNaN("0x10"));    // false
console.log(Number("0x10"));   // 16

In the above example, the isNaN() method is giving the correct output for the first two strings. But, why is it returning false in the case of the string “0x10”?

Well, this is because the string “0x10” is the hexadecimal representation of the number 16. Hence, the method isNaN() returning false.

If you pass an empty string or a string that contains only white spaces to the isNaN() method, it returns false. This is because an empty string or a string with only white spaces when converted to a number results in 0(zero).

console.log(isNaN(""));       // false
console.log(Number(""));      // 0

console.log(isNaN("   "));    // false
console.log(Number("   "));   // 0