Convert a String to a Number in JavaScript

Posted By : Sushmit Gaur | 03-Sep-2018

JavaScript provides many ways to convert a string value into a number.

1. Number Object (without the "new" keyword) :

const count = Number('1234') // Output => 1234

This takes care of the decimals as well.

 

Output for separators between digits:

Number('10,000') // Output => NaN
Number('10.00') // Output => 10
Number('10000') // Output => 10000

In case if string with decimal seperator needs to be parsed then Intl.NumberFormat should be used.

 

2. Use PARSEINT() Or PARSEFLOAT() :

const count = parseInt('1234', 10) // Ouput => 1234

the second parameter is the radix, always 10 for decimal numbers, if missed the conversion might try to guess the radix and give unexpected results.

 

parseInt() can parse a string that does not only contain a number:

parseInt('10 lions', 10) // Ouput => 10

 

if the string does not start with a number, Output will be NaN (Not a Number):

parseInt("I'm 10", 10) // Output => NaN

 

Output for separators between digits:

parseInt('10,000', 10) // Output => 10     ?
parseInt('10.00', 10) // Output => 10     (decimals are dropped)
parseInt('10.000', 10) // Output => 10    (decimals are dropped)
parseInt('10.20', 10) // Output => 10     (decimals are dropped)
parseInt('10.81', 10) // Output => 10     (decimals are dropped)
parseInt('10000', 10) // Output => 10000

If the decimal part needs to be retained parseFloat() should be used:

parseFloat('10,000', 10) //10     ?
parseFloat('10.00', 10) // Output => 10     (decimals are dropped)
parseFloat('10.000', 10) // Output => 10    (decimals are dropped)
parseFloat('10.20', 10) // Output => 10.2   (decimals are dropped)
parseFloat('10.81', 10) // Output => 10.81  (decimals are dropped)
parseFloat('10000', 10) // Output => 10000 

 

3. Use the unary operator + before the string:

+'10,000'  // Output => NaN
+'10.000'  // Output => 10
+'10.00'  // Output => 10 
+'10.20'  // Output => 10.2
+'10.81'  // Output => 10.81
+'10000' // Output => 10000

 

4. Use Math.floor() :

Math.floor('10,000') // Output => NaN
Math.floor('10.000') // Output => 10
Math.floor('10.00') // Output => 10
Math.floor('10.20') // Output => 10
Math.floor('10.81') // Output => 10
Math.floor('10000') // Output => 10000

 

5. Use "* 1" :

'10,000' * 1 // Output => NaN
'10.000' * 1 // Output => 10
'10.00' * 1 // Output => 10
'10.20' * 1 // Output => 10.2
'10.81' * 1 // Output => 10.81
'10000' * 1 // Output => 10000

 

Performance :

Performance-wise "* 1" is 10x faster than other alternatives.

About Author

Author Image
Sushmit Gaur

Sushmit is a self taught programmer, having experience in UI Development for Web Applications. With Experience of 3 months as an intern in React.js technology looking forward to learn new skill set and challenges for further assessment in career.

Request for Proposal

Name is required

Comment is required

Sending message..