Determine whether a string is numeric in JavaScript
This post will discuss how to determine whether a string is numeric in JavaScript.
1. Using isNaN() method
The recommended solution is to use the isNaN() method, which tests a value for NaN (Not a Number). To illustrate, consider the following code, where the isNumeric() returns true when the given string is a number and false otherwise.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const isNumeric = n => !isNaN(n); /* Numeric strings */ isNumeric('1'); isNumeric('+1'); isNumeric('-1'); isNumeric('1.0'); isNumeric('1.1'); isNumeric('1e10'); isNumeric('2e-5'); isNumeric('0xFFFFFF'); isNumeric('Infinity'); isNumeric('-Infinity'); /* Non-Numeric strings */ isNumeric('NaN'); isNumeric('str1'); |
2. Using Number() function
A simple and fairly efficient solution to convert the given string to a numerical value is using Number as a function, which returns NaN if it cannot be converted into a number.
This is demonstrated below, where we cast the return value of the Number() function to be boolean using !!expr.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const isNumeric = n => !!Number(n); /* Numeric strings */ isNumeric('1'); isNumeric('+1'); isNumeric('-1'); isNumeric('1.0'); isNumeric('1.1'); isNumeric('1e10'); isNumeric('2e-5'); isNumeric('0xFFFFFF'); isNumeric('Infinity'); isNumeric('-Infinity'); /* Non-Numeric strings */ isNumeric('NaN'); isNumeric('str1'); |
That’s all about checking if a string is numeric in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)