Section 24.150. parseInt( ): convert a string to an integer


24.150. parseInt( ): convert a string to an integer

ECMAScript v1

24.150.1. Synopsis

 parseInt(s) 

parseInt(s, radix)

24.150.1.1. 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 10or in base 16 if it begins with 0x or 0X. If this argument is less than 2 or greater than 36, parseInt( ) returns NaN.

24.150.1.2. 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.

24.150.2. 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 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.

24.150.3. 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 

24.150.4. 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 numbers, or hexadecimal numbers with the 0x or 0X prefix.

24.150.5. See Also

 isNaN( ), parseFloat( ) 




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net