JavaScript » Functions » parseInt

Syntax:

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.

Examples

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"))
50
50
32
71
37
NaN
Explanation:

If the first non-whitespace character is not numeric, the function returns the Not-a-Number value NaN.

Code:
document.write(parseInt("110", 2))
6
Explanation:

You can use the optional radix argument to convert a binary number string to the decimal (base 10) equivalent.

Code:
document.write(parseInt("0xD9", 16))
217
Explanation:

You can use the optional radix argument to convert a hexidecimal number string to the decimal (base 10) equivalent.

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
Explanation:

You can use the isNaN function to see if the returned value is a NaN.