How to convert a string to a number
Short answer
The Number() function converts the whole string:
console.log(Number('42') + 1);Output:
43A string with extra characters
Number() returns NaN for such a string, while parseInt() and parseFloat() parse the digits at the start:
console.log(Number('42px'));
console.log(parseInt('42px', 10));
console.log(parseFloat('3.14em'));Output:
NaN
42
3.14Checking the result
NaN is not equal even to itself, so check for it with Number.isNaN():
const value = Number('abc');
console.log(Number.isNaN(value));Output:
trueThe unary plus
The + before a value works like Number(). It is short, but Number() is easier to read:
const input = '15';
console.log(+input + 5);Output:
20Common mistake
Values from forms are strings, and + with a string glues instead of adding. Convert before calculating:
const quantity = '2';
console.log(quantity + 1);
console.log(Number(quantity) + 1);Output:
21
3Functions used in this recipe
- Number() — Converts a value to a number.
- parseInt — Converts a string to an integer.
- parseFloat — Reads a floating-point number from the start of a string.
- Number.isNaN — Checks that a value is NaN, without type conversion.