Cover image for Best Ways to Convert a String to Number in Javascript

Best Ways to Convert a String to Number in Javascript

newbiebr profile image Arthur Dao Originally published at hadev.fr ・2 min read

Converting a string to number (or a number to string) might be one of the most common operations in Javascript. There are always several ways to convert a string to number, what is the best one?


The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

// expected output: 42

// expected output: 42

parseInt() can also convert non-decimal numbers by using the second optional parameter.

console.log(parseInt("f", 16));
// expected output: 15

// we don't need to pass the second parameter because parseInt
// detect the prefix "0x" which means the number is hexadecimal
// expected output: 15


The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.

// expected output: 4.23

// expected output: 4.23

// expected output: NaN


Number is a Javascript built-in object. It can be used to convert string to integer or floating point number.

// expected output: 42

// expected output 42.3

However, it cannot handle trailing non-numeric characters like parseInt or parseFloat

// expected output: NaN

// expected output NaN

Mutiply by 1

Using the feature of Javascript of assimilating data types, we can convert a string to number easily.

console.log("42" * 1);
// expected output: 42

console.log("42.3" * 1);
// expected output 42.3

Just like Number, this method cannot handle trailing non-numeric characters.

Unary operator '+'

This might be the simplest way to convert a string to number in Javascript even though it's not very well-known.

// expected output: 42

// expected output 42.3

Same as the 2 approches above, this approach cannot handle trailing non-numeric characters.


All the methods have cons and pros, make sure to choose the one that fit your need, your team and your work environment.

Posted on May 20 by:


markdown guide

I usually use +myString or really probably +myStringOrNumberImNotQuiteSureDependsOnUserInput

I also discovered:

var flooredNumber = someNumber | 0 recently which is slightly faster than Math.floor()


Thanks for sharing!

+ is my preferred one too. The only problem with + is it does not handle trailing character like:

console.log(+"42a"); // output: NaN