parseInt( ) |
convert a string to an integer |
Availability
JavaScript 1.0; JScript 1.1; ECMAScript v1
Synopsis
parseInt(s)
parseInt(s, radix)
Arguments
- s
-
The string to be parsed.
- radix
-
An optional integer argument that represents the radix (i.e., base)
of the number to be parsed. If this argument is omitted or is 0, the
number is parsed in base 10, or in base 16 if it begins with
"0x" or "0X". If this argument is less than 2
or greater than 36, parseInt( ) returns
NaN.
Returns
The parsed number, or NaN if
s does not begin with a valid integer. In
JavaScript 1.0, parseInt( ) returns 0 instead of
NaN when it cannot parse
s.
Description
parseInt( ) parses and returns the first number
(with an optional leading minus sign) that occurs in
s. Parsing stops, and the value is
returned, when parseInt( ) encounters a character
in s that is not a valid digit for the
specified radix. If
s does not begin with a number that
parseInt( ) can parse, the function returns the
not-a-number value NaN. Use the isNaN(
) function to test for this return value.
The radix argument specifies the base of
the number to be parsed. Specifying 10 makes the parseInt(
) parse a decimal number. The value 8 specifies that an
octal number (using digits 0 through 7) is to be parsed. The value 16
specifies a hexadecimal value, using digits 0 through 9 and letters A
through F. radix can be any value between
2 and 36.
If radix is 0 or is not specified,
parseInt( ) tries to determine the radix of the
number from s. If
s begins (after an optional minus sign)
with 0x, parseInt( ) parses the
remainder of s as a hexadecimal number. If
s begins with a 0, the
ECMAScript v3 standard allows an implementation of parseInt(
) to interpret the following characters as an octal number
or as a decimal number. Otherwise, if s
begins with a digit from 1 through
9, parseInt( ) parses it as a
decimal number.
Example
parseInt("19", 10); // Returns 19 (10 + 9)
parseInt("11", 2); // Returns 3 (2 + 1)
parseInt("17", 8); // Returns 15 (8 + 7)
parseInt("1f", 16); // Returns 31 (16 + 15)
parseInt("10"); // Returns 10
parseInt("0x10"); // Returns 16
parseInt("010"); // Ambiguous: returns 10 or 8
Bugs
When no radix is specified, ECMAScript v3
allows an implementation to parse a string that begins with
"0" (but not "0x" or "0X") as an
octal or as a decimal number. To avoid this ambiguity, you should
explicitly specify a radix or leave the radix unspecified only when
you are sure that all numbers to be parsed will be decimal or
hexadecimal numbers with the "0x" or "0X"
prefix.
In JavaScript 1.0, NaN is not supported, and
parseInt( ) returns 0 instead of
NaN when it cannot parse
s. In this version of the language,
parseInt( ) cannot distinguish between malformed
input and a the legal input "0".
See Also
isNaN( ), parseFloat( )
|