JavaScript Reference ยท Number and BigInt
Number.parseInt()
Reference for Number.parseInt(): parsing integers from strings in any radix from 2 to 36, partial parsing, hex prefixes, NaN results and common pitfalls.
Number.parseInt() reads a string from the left and returns the integer it finds there, in the number base you choose with the second argument. It skips leading whitespace, accepts an optional sign and stops at the first character that is not a valid digit for the base. If no digits are found, the result is NaN.
It is the same function object as the global parseInt(). Always pass the radix explicitly so the result does not depend on the string's prefix.
Number.parseInt(string, radix)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Number.parseInt(string) Number.parseInt(string, radix)
| Name | Description |
|---|---|
string |
The value to parse. Non-strings are converted to a string first. |
radix |
Optional integer from 2 to 36: the base of the number in string. If it is omitted or 0, base 10 is used, except that a 0x or 0X prefix selects base 16. Any other value outside 2-36 gives NaN. |
Return value: an integer, or NaN if no digits could be read.
Exceptions: none for ordinary values; a Symbol throws a TypeError.
Usage notes
- Always pass a radix.
parseInt(text, 10)says what you mean and avoids the0xsurprise. - It truncates.
parseInt("3.99")is3. To round, useMath.round(Number(text)); to parse a decimal, useparseFloat(). - Do not use it to floor numbers.
parseInt(0.0000005)is5because the number is converted to the string"5e-7"first. UseMath.trunc()orMath.floor(). - Trailing text is ignored.
"42px"gives42. For strict validation useNumber(text)together withNumber.isInteger(). map(parseInt)is a bug, because the index becomes the radix. Pass an arrow function or useNumber.- Letters as digits: for radix above 10, letters
a-z(case-insensitive) stand for 10-35. - Precision: results above
Number.MAX_SAFE_INTEGERmay be rounded. UseBigInt("123...")for exact huge integers. - Empty or whitespace-only input is
NaN, unlikeNumber("")which is0. - Modern code often uses
Number()for whole strings, andparseInt()only when the text has a suffix or a non-decimal base.
Browser support
Supported in all current browsers. The Number.parseInt alias arrived with ES2015, and the global function has existed since the beginning.