The Number parseInt() method
By Flavio Copes
Learn how the JavaScript Number.parseInt() method parses a string into an integer, including extracting a leading number and using the radix for octal or hex.
The Number.parseInt() method parses a string and returns an integer:
Number.parseInt('10') //10
Number.parseInt('10.00') //10
Number.parseInt('237,21') //237
Number.parseInt('237.21') //237
Number.parseInt('12 34 56') //12
Number.parseInt(' 36 ') //36
Number.parseInt('36 is my age') //36
How the parsing works
Number.parseInt() skips any leading whitespace, then reads characters from the start of the string for as long as they form a valid integer. As soon as it meets a character that doesn’t fit, it stops and returns what it collected so far.
That’s why '237,21' returns 237: the comma stops the parsing. Same for '237.21', the decimal part is dropped, not rounded.
This also means it can extract the first number from strings containing words, but the string must start with a number:
Number.parseInt('I am Flavio and I am 36') //NaN
Note that Number.parseInt() is the same function as the global parseInt(). It was added to the Number object in ES2015 to group the number utilities in one place:
Number.parseInt === parseInt //true
The radix
You can add a second parameter to specify the radix, the base of the numeral system. Radix 10 is the default but you can use octal or hexadecimal number conversions too:
Number.parseInt('10', 10) //10
Number.parseInt('010') //10
Number.parseInt('010', 8) //8
Number.parseInt('10', 8) //8
Number.parseInt('10', 16) //16
Strings starting with 0x or 0X are automatically parsed as hexadecimal:
Number.parseInt('0x1F') //31
In very old JavaScript engines a leading zero triggered octal parsing, which is why you still see advice to always pass the radix explicitly. Modern engines parse '010' as 10, as shown above, but being explicit doesn’t hurt when you don’t control the input format.
Watch out for NaN
When the string does not start with something parseable, the result is NaN. An empty string gives NaN too. Since NaN is not equal to itself, check for it with Number.isNaN():
const age = Number.parseInt('')
age === NaN //false, this check never works
Number.isNaN(age) //true
One more gotcha: exponent notation is not understood. The string '1e3' means 1000 as a number, but parseInt() reads the 1, stops at the e, and returns 1:
Number.parseInt('1e3') //1
Number.parseFloat('1e3') //1000
If your strings can contain decimals or exponent notation, reach for Number.parseFloat() or Number() instead.
Related posts about js: