Number.parseInt()
Identical to the global parseInt — the same function object, re-exposed on Number in ES2015. Its lenient parsing is useful for things like "42px" and disastrous everywhere else.
Demo
Parsing runs from the left and stops at the first character that is not a digit in the given base, so '42px' gives 42 while 'px42' gives NaN — leading junk is fatal, trailing junk is ignored. The fourth case catches people out: '1e3' parses as 1, because 'e' is not a decimal digit and parsing halts there. Number('1e3') gives 1000, because it understands exponent notation. That difference alone decides which of the two you should be using.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| string | string | yes | The text to parse. Leading whitespace is skipped; parsing stops at the first invalid character. A non-string argument is converted to a string FIRST, which is how tiny numbers parse wrongly. |
| radix | number | no (10) | The base, 2 to 36. Omitted it is 10, except that a 0x prefix forces 16. Always pass it explicitly. |
Return value
number — An integer parsed from the START of the string, stopping at the first character that is not a valid digit. NaN if nothing valid was found at all.
Common patterns
const n = parseInt(input, 10);
strings.map(s => parseInt(s, 10));
const n = Number(input); // NaN for "42px"
Examples
Pitfalls
['10', '10', '10'].map(parseInt)
['10', '10', '10'].map(s => parseInt(s, 10))
parseInt(0.0000005)
Math.trunc(0.0000005)
parseInt('42abc', 10)
Number('42abc')
parseInt('0x1f')
parseInt('0x1f', 10)
When to use
- Pulling a number off the front of text — "42px", "3 items"
- Parsing in a non-decimal base, with an explicit radix
- Reading values from formats that append units
- Validating user input → Number, which rejects trailing junk
- Values in exponent notation → Number
- Truncating a number you already have → Math.trunc
- Decimals matter → parseFloat
Notes
FAQ
Number for validation — it rejects anything not entirely numeric and understands exponent notation. parseInt when you deliberately want the leading digits of a string that has other characters after them, like a CSS length.
Number('42px'); // NaN — strict parseInt('42px', 10); // 42 — lenient