How to Check if String is Valid Number

Often web developers need to determine with a string is a valid number or not using JavaScript. JavaScript is a powerful programming language used by almost every website and web application in the world. It allows you to easily with with data as well as DOM elements. In this article, we will learn how to do this.

Why Check if String is Valid Number

In JavaScript, there is no strict data type casting, unless you explicitly specify it in your program. It means that numbers can be floats, integers or even in scientific notation. On the other hand, strings can be alphabets, numbers, or even special characters.

If your website or application needs to use a number, and your data is available as strings, then you need to carefully validate whether the string is actually number or not. This is especially true in case of financial websites and applications. You also need to do this on form submissions and data processing to avoid mischievous inputs. Otherwise, non-numerical data might creep into your site’s database. It can also lead to bugs and security vulnerability on your site.

How to Check if String is Valid Number

Here are the different ways to check if a string is a valid number in JavaScript.

1. Using isNaN

The isNaN() function (NaN – Not a Number) allows you to check if a given value is a number or not. The provided value may be a string or number or some other data type. It returns true if the value is not a number, else it returns false. Here is its syntax.

Number.isNaN(value)

Here are some examples to demonstrate its use.

a = 1234;
b= '1234';
console.log(isNaN(a)); // output is false
console.log(isNaN(b)); // output is false

a = 'pqr';
b= '1234px';
console.log(isNaN(a)); // output is true
console.log(isNaN(b)); // output is true

In the above code, the first two values are numbers so isNaN() returns false. The next 2 values are alphanumeric or pure string values so it returns isNaN().

It is important to note that this function converts input value into number before checking it. So you need to be careful. If the value is not a number, but gets converted into a number, even if it is of a different value, then isNaN() function may return false result, indicating a false positive. This is also true in case of empty strings as shown.

a = '';
console.log(isNaN(a));

To overcome this problem, you can prefix the value with a unary ‘+’ operator which will automatically convert the string into a number, before passing it to isNaN() function.

a = 'pqr';
b= '1234px';
console.log(isNaN(+a)); // output is true
console.log(isNaN(+b)); // output is true

2. Using Regular Expressions

You can also use test() function along with regular expressions to check if a value is a number or not. Here is a regular expression to cover all integers.

^-?\d+$

Here is an example that uses the above expression to check whether a value is number or not.

value = 123;
console.log(/^-?\d+$/.test(value)); // output is true

value = -123;
console.log(/^-?\d+$/.test(value)); // output is true

The above regular expression does not work for numbers with decimal points.

value = -123.56;
console.log(/^-?\d+$/.test(value)); // output is false

If you also want to cover numbers with decimal point then you need to modify your regular expression to the following.

^-?\d+(\.\d+)?$

Here are a couple of examples to check if a value with decimal point is a number or not.

value = -123.56;
console.log(/^-?\d+(\.\d+)?$/.test(value)); // output is true

JavaScript also uses numbers with scientific notations such as 1e3. If you want to check if these are also numbers then you need to use the following regular expression.

^-?\d+(\.\d+)?(e-?\d+)?$

Here is an example to check whether such a value is number or not.

value = 1.23e4;
console.log(/^-?\d+(\.\d+)?(e-?\d+)?$/.test(value)); // output is true

You can convert the above checks into a function for convenience.

value = 1.23;
function is_number(value) {
return /^-?\d+$/.test(value);
}
console.log(is_number(value)); // output is false

3. Using Number() function

The Number() function will convert input value into a number and return NaN if the value is an invalid number. We can use it as follows to check if a value is number or not.

!isNaN(Number(value))

Here is an example, where we have wrapped the above code in a function for convenience.

function is_number(value) {
return !isNaN(Number(value));
}

Here is an example to use the above function.

dat1 = '1.23a';
dat2 = '1.23';

console.log(is_number(dat1)); // output is false
console.log(is_number(dat2)); // output is true

In the above code, the first example is an alphanumeric string so our function returns false value. In second case, the value is a decimal number so the function returns true value.

4. Using parseFloat and parseInt

In JavaScript, parseFloat function converts a given value into float and parseInt function converts a given value into integer. In case, it is an invalid number, then both these functions return NaN value. So we can call isNaN() function on the output of parseFloat/parseInt functions to check if a given value is a number or not.

data = 'a1.23a';
console.log(!isNaN(parseFloat(data))); // output is false

In the above code, we call parseFloat() function on data variable. Since it is an alphanumeric string, it returns NaN. isNaN() function will therefore return true. We negate this output using ‘!’ operator, to obtain false result.

It is important to note that parseFloat and parseInt functions may sometimes convert even alphanumeric strings into proper floats and int. In such cases, you may get a false positive result. So we need to be careful. Here is an example to demonstrate it.

data = 'a1.23a';
console.log(!isNaN(parseInt(data))); // output is false

5. Using isFinite

isFinite() function returns true if input value is a finite number. It returns NaN on infinite number and NaN values. You can use it to easily find if a value is a number or not.

a = 'pqr';
b= '1234px';
console.log(isFinite(a)); // output is false
console.log(isFinite(b)); // output is false

6. Combining Solutions

We have seen many different ways to check if a value is a number or not. Since most of them have some exception use case or the other, it is always better to create a comprehensive solution by combining one or more of the above solutions.

You can use a combination of isNaN and parseFloat to robustly check if a string is a number or not.

function is_number(value) {
return !isNaN(value) && !isNaN(parseFloat(value));
}

console.log(is_number(1234.23)); // output is true
console.log(is_number('abc')); // output is false

If you want to make it more comprehensive, then you can also include isFinite() function in it.

function is_number(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

console.log(is_number(1234.23)); // output is true
console.log(is_number('abc')); // output is false

Conclusion

In this article, we have learnt several simple ways to easily check if a string is a valid number or not in JavaScript. If you want to check for simple integers and floats then you can use functions such as isNaN(), Number(), parseFloat() or parseInt(). If you want to check for complex number formats such as those using scientific or decimal notation, you can use regular expressions along with test() function for this purpose. You may also use a combination of these methods to create a more robust method to check whether a string is a number or not.

Also read:

How to Get Difference Between Two Arrays in JavaScript
How to Remove Character from String in JavaScript
How to Replace All Occurrences of Substring in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *