The JavaScript parseInt() function parses a string and returns the first integer in a string.
There are two arguments one of which is mandatory string argument that is the string which is parsed to return the integer. The other argument is the optional radix argument that 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 begins with "0x", the radix is 16 (hexadecimal)
- If the string begins with "0", the radix is 8 (octal). This feature is deprecated
- If the string begins with any other value, the radix is 10 (decimal)
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 by the parseInt() function, 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.
Here are some examples of JavaScript parseInt() Function
document.write("<BR>" + parseInt("15"))
document.write("<BR>" + parseInt("12.12345"))
document.write("<BR>" + parseInt("45.00000000"))
document.write("<BR>" + parseInt("23.348 44.218 55.405"))
document.write("<BR>" + parseInt(" 55 aardvarks"))
document.write("<BR>" + parseInt("Year 2002"))
The output of the code above will be:
15
12
45
23
55
NaN
Want automatic updates?
Subscribe to our RSS feed
or
Get Email Updates
sent directly to your inbox!
Currently rated 3.0 by 4 people
- Currently 3/5 Stars.
- 1
- 2
- 3
- 4
- 5