loading...
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?

parseInt()

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

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

console.log(parseInt("42abc"));
// expected output: 42

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

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

console.log(parseInt("0xf"));
// we don't need to pass the second parameter because parseInt
// detect the prefix "0x" which means the number is hexadecimal
// expected output: 15

parseFloat()

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

console.log(parseFloat(4.23));
// expected output: 4.23

console.log(parseFloat('4.23abc'));
// expected output: 4.23

console.log(parseFloat('abc'));
// expected output: NaN

Number()

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

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

console.log(Number("42.3"));
// expected output 42.3

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

console.log(Number("42abc"));
// expected output: NaN

console.log(Number("42.3abc"));
// 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.

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

console.log(+"42.3");
// expected output 42.3

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

Conclusion

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:

Discussion

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