How to Convert a String to a Number in JavaScript
Learn how to convert a string to a number using JavaScript.
JavaScript provides several ways to convert a string value into a number.
Best: Use the Number Object
The best and recommended way is to use the Number object in a non-constructor context, without the new
keyword:
1 | const count = Number('1234'); // 1234 |
This method takes care of decimal values as well.
It’s important to note that the Number object is a wrapper object that can perform various operations. If you use the constructor (new Number("1234")
), it will return a Number object instead of a number value, so be careful with that.
Watch out for separators between digits when using the Number object:
1 | Number('10,000'); // NaN |
In case you need to parse a string with decimal separators, it’s recommended to use Intl.NumberFormat
instead.
Other Solutions
Use parseInt() and parseFloat()
Another good solution for integers is to use the parseInt()
function:
1 | const count = parseInt('1234', 10); // 1234 |
Make sure to include the second parameter, which is the radix. It should always be 10 for decimal numbers to avoid unexpected results.
parseInt()
tries to extract a number from a string that contains additional characters:
1 | parseInt('10 lions', 10); // 10 |
But if the string does not start with a number, it will return NaN
(Not a Number):
1 | parseInt("I'm 10", 10); // NaN |
Similar to the Number object, parseInt()
is not reliable with separators between the digits:
1 | parseInt('10,000', 10); // 10 ❌ |
If you want to retain the decimal part and not just the integer part, use parseFloat()
. Unlike its parseInt()
counterpart, it only takes one argument, which is the string to convert:
1 | parseFloat('10,000'); // 10 ❌ |
Use the Unary Operator +
One “trick” is to use the unary operator +
before the string:
1 | +'10,000'; // NaN ✅ |
Notice how it returns NaN
in the first example, which is the correct behavior because it’s not a number.
Use Math.floor()
Similar to the unary operator +
, but only returns the integer part, is to use Math.floor()
:
1 | Math.floor('10,000'); // NaN ✅ |
Use * 1
Another option, which is generally faster, is to use * 1
. It behaves like the unary operator +
and does not perform conversion to an integer if the number is a float.
1 | '10,000' * 1; // NaN ✅ |
Performance
Each of these methods has different performance characteristics depending on the environment. In general, * 1
is considered the fastest option, being 10x faster than the others in some cases.
Use JSPerf to test and compare the performance yourself.
Tags: JavaScript, string to number, parseInt, parseFloat, unary operator, Math.floor, performance