JavaScript: The Definitive Guide

Previous Chapter 21
JavaScript Reference
Next
 

parseInt() Function

Name

parseInt() Function---convert a string to an integer

Availability

Navigator 3.0; partial support in Navigator 2.0 and Internet Explorer 3.0

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.

Returns

The parsed number, or NaN, if s does not begin with a valid integer. Because Navigator 2.0 and Internet Explorer 3.0 do not support NaN, those browsers returns 0 when s cannot be parsed.

Description

parseInt() is a built-in function in JavaScript; it is a core part of the language, and is not a method of any object.

parseInt() parses and returns the first number that occurs in s. Parsing stops, and the value is returned, when parseInt() encounters a character in s that is not a valid numeral for the specified radix. If s does not begin with a number that parseInt() can parse, then the function returns NaN, a reserved value that represents "not-a-number." You can test for the NaN value with the isNaN() function. If NaN is used with arithmetic operations, the result will always be NaN.

In Navigator 2.0 (except on Unix platforms) and in Internet Explorer 3.0, NaN is not implemented, and parseInt() returns 0 instead of NaN. For these browsers parseInt() that does not distinguish between a malformed string value and a legal value 0.

radix 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 if it is not specified, parseInt() tries to determine the radix of the number from s. If s begins with 0x, then parseInt() parses the remainder of s as a hexadecimal number. If s begins with a 0, then parseInt() parses the number in octal. Otherwise, if s begins with a digit 1 through 9, then parseInt() parses it as a decimal number.

Bugs

In Navigator 2.0 (except Unix platforms) and Internet Explorer 3.0, the NaN return value is not implemented, and so parseInt() returns 0 when it cannot parse a number. When you receive this return value on those platforms, you must perform additional tests to determine whether the string contains illegal input or actually contains the value 0.

See Also

"isNaN()", "parseFloat()"


Previous Home Next
parseFloat() Book Index Password

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell
This HTML Help has been published using the chm2web software.