Function:  parseInt


parseInt(string, radix)
 
The top-level function, parseInt, find the first integer in a string.
 
There are two arguments. The mandatory string argument is the string which is presumed to contain an integer. The optional radix argument specifies the base of the integer and can range from 2 to 36. For example, 16 is the hexidecimal base (0123456789ABCDEF).
 
If no radix argument is provided or if it is assigned a value of 0, the function tries to determine the base. If the string starts with a 1-9, it will be parsed as base 10. If the string starts with 0x or 0X it will be parsed as a hexidecimal number. If the string starts with a 0 it will be parsed as an octal number. (Note that just because a number starts with a zero, it does not mean that it is really octal.)
 
After determining if the first character in the string argument is a number, the parseInt function parses the string from left to right until the end of the number or a decimal point is encountered, then it discards any characters that occur after the end of the number (including a decimal point and all numbers after the decimal point), and finally it returns the number as an integer (not as a string).
 
Only the first integer in the string is returned, regardless of how many other numbers occur in the string. This function does not return decimal points nor numbers to the right of a decimal.
 
If the first non-whitespace character is not numeric, the function returns the Not-a-Number value NaN.
 
Code:
document.write("<BR>" + parseInt("50"))
document.write("<BR>" + parseInt("50.12345"))
document.write("<BR>" + parseInt("32.00000000"))
document.write("<BR>" + parseInt("71.348  92.218  95.405"))
document.write("<BR>" + parseInt("         37 aardvarks"))
document.write("<BR>" + parseInt("Awarded the best wine of 1992"))

 
Output:
50
50
32
71
37
NaN

 
You can use the optional radix argument to convert a binary number string to the decimal (base 10) equivalent.
 
Code:
document.write(parseInt("110", 2))

 
Output:
6
 
You can use the optional radix argument to convert a hexidecimal number string to the decimal (base 10) equivalent.
 
Code:
document.write(parseInt("0xD9", 16))

 
Output:
217
 
You can use the isNaN function to see if the returned value is a NaN.
 
Code:
pet = "Rachel has 312 baby aardvarks"
CheckNum = parseInt(pet)
if(isNaN(CheckNum))
   {
     document.write("<BR>Sorry, CheckNum is a NaN")
     document.write("<BR>Left-most character = " + pet.substring(0,1))
   }

 
Output:
Sorry, CheckNum is a NaN
Left-most character = R


Copyright 1999-2001 by Infinite Software Solutions, Inc. All rights reserved.
Trademark Information