JavaScript parseInt()
Function
Definition and Usage
The parseInt()
function parses a string and returns an integer.
When the radix
parameter is 0 or not provided, parseInt()
will determine the base of the number from the string.
When the radix
parameter is omitted, JavaScript defaults to the following bases:
If the string starts with "0x",
parseInt()
parses the rest of the string as a hexadecimal number.If the string starts with 0, ECMAScript v3 allows
parseInt()
to interpret the subsequent characters as an octal or hexadecimal number.If the string starts with a digit from 1 to 9,
parseInt()
parses it as a decimal number.
Syntax
Parameter | Description |
---|---|
string | Required. The string to be parsed. |
radix | Optional. The base of the number to be parsed, which ranges from 2 to 36. |
Browser Support
All major browsers support the parseInt()
function.
Tips and Notes
Note: Only the first number in the string is returned.
Note: Leading and trailing spaces are allowed.
Note: If the first character of the string cannot be converted to a number, parseInt()
returns NaN.
Note: Older browsers default to an octal base when the string starts with "0". ECMAScript 5 defaults to a decimal base.
Examples
We will use parseInt()
to parse different strings:
document.write(parseInt("10") + "<br>");
document.write(parseInt("10.33") + "<br>");
document.write(parseInt("34 45 66") + "<br>");
document.write(parseInt(" 60 ") + "<br>");
document.write(parseInt("40 years") + "<br>");
document.write(parseInt("He was 40") + "<br>");
document.write("<br>");
document.write(parseInt("10", 10) + "<br>");
document.write(parseInt("010") + "<br>");
document.write(parseInt("10", 8) + "<br>");
document.write(parseInt("0x10") + "<br>");
document.write(parseInt("10", 16) + "<br>");
The above examples output the following results:
document.write(parseInt("10") + "<br>");
document.write(parseInt("10.33") + "<br>");
document.write(parseInt("34 45 66") + "<br>");
document.write(parseInt(" 60 ") + "<br>");
document.write(parseInt("40 years") + "<br>");
document.write(parseInt("He was 40") + "<br>");
document.write("<br>");
document.write(parseInt("10", 10) + "<br>");
document.write(parseInt("010") + "<br>");
document.write(parseInt("10", 8) + "<br>");
document.write(parseInt("0x10") + "<br>");
document.write(parseInt("10", 16) + "<br>");
Note: Older browsers, using older versions of ECMAScript (before ECMAScript 5), default to an octal base when the string starts with "0". ECMAScript 5 defaults to a decimal base.