This post will discuss how to convert a numeric string to a number in JavaScript.

1. Using Number() function

A simple solution is to use the Number() function, that takes a string as the argument and returns a number converted from the string. If the string is not a valid number, it returns NaN. For example:

Download  Run Code

 
This function handles the decimal strings and the null value. If we add the new keyword, Number() returns a Number object instead of the primitive number.

Download  Run Code

2. Using parseInt() function

The parseInt() function takes a string as the first argument and an optional radix (base) as the second argument, and returns an integer parsed from the string. If the string is not a valid number, it returns NaN (not a number). For example:

Download  Run Code

 
This function is same as the Number.parseInt() function. This function it will ignore any leading or trailing whitespace in the string, and will stop parsing only when it encounters an invalid character.

Download  Run Code

3. Unary plus operator

We can use unary plus (+) operator to convert a string to a number by placing it before the string. It works similarly to the Number() function, but with a shorter syntax. It also handles the decimal strings, and returns NaN for non-numeric strings. For example:

Download  Run Code

 
This is the fastest and preferred way of converting a string into a number. The unary negation (-) can also be used in the following manner.

Download  Run Code

4. Using Math.floor() function

If the string is guaranteed to be a valid integer, we can use the Math.floor() function to convert a string to a number. This function will remove the fractional part from the string, if any. For example:

Download  Run Code

That’s all about converting a numeric string to a number in JavaScript.