JavaScript Reference ยท Global Functions and Values
The parseInt() function
Reference for JavaScript parseInt(): converting strings to integers, the radix argument, partial parsing, NaN results and how it differs from Number().
parseInt() reads a string from the left and returns the integer it finds there. It stops at the first character that cannot be part of a number, so "42px" becomes 42. If the string does not start with a number at all, the result is NaN.
The function is the same object as Number.parseInt. It exists mainly for text that carries a number plus something else, such as CSS values or user input with units.
parseInt("42px"); // 42 parseInt("ff", 16); // 255
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
parseInt(string) parseInt(string, radix)
| Name | Description |
|---|---|
string |
The value to parse. Anything that is not a string is converted to one first. Leading whitespace is ignored. |
radix |
Optional integer from 2 to 36 giving the base of the number. If omitted or 0, the base is 10, except that a 0x or 0X prefix selects 16. |
Return value: an integer, or NaN if the first non-whitespace characters cannot form a number. A radix outside 2 to 36 also gives NaN.
Exceptions: none for ordinary values. A Symbol, or an object whose string conversion throws, causes a TypeError or the thrown error.
Usage notes
- Always pass the radix (usually
10). The default is predictable in modern engines, but an explicit radix makes the intent clear and avoids the hexadecimal surprise for strings that start with0x. - Partial parsing is a feature and a trap.
parseInt("12abc")is12, which can hide bad input. When the whole string must be a number, useNumber()or check withNumber.isInteger(Number(text)). - It truncates toward zero.
parseInt("-3.9")is-3. For rounding useMath.round(),Math.floor()orMath.trunc()on a number instead. - A sign is allowed, one
+or-directly before the digits. Digits only valid in the radix count:parseInt("19", 8)is1. - Non-strings are converted first. Passing a number such as
0.0000005converts it to the string"5e-7"and returns5. Do not useparseInt()to round numbers. - No numeric separators or binary/octal prefixes.
"1_000"gives1, and"0b11"gives0(the parser stops atb). - Large values lose precision beyond
Number.MAX_SAFE_INTEGER. UseBigInt("...")for exact big integers. - Using it as a callback is a classic bug:
["1", "2", "3"].map(parseInt)passes the index as the radix and returns[1, NaN, NaN]. Write.map(s => parseInt(s, 10))or.map(Number).
Browser support
parseInt() is available in every browser and JavaScript runtime.
Related
parseFloat(),isNaN(),Number(),Number.parseInt()- Lessons: Type conversion, Numbers