Home >Web Front-end >JS Tutorial >JavaScript parseInt() function
Definition and Usage
parseInt() function parses a string and returns an integer.
Syntax
parseInt(string, radix)
Parameter Description
string Required. The string to be parsed.
radix
Optional. Represents the base of the number to be parsed. The value is between 2 ~ 36.
If this parameter is omitted or its value is 0, the number will be parsed in base 10. If it starts with "0x" or "0X" it will be base 16.
If the parameter is less than 2 or greater than 36, parseInt() will return NaN.
Return Value
Returns the parsed number.
Explanation
When the value of parameter radix is 0, or the parameter is not set, parseInt() will determine the base of the number based on string.
For example, if string starts with "0x", parseInt() will parse the rest of string into hexadecimal integers. If the string begins with 0, ECMAScript v3 allows an implementation of parseInt() to parse the following characters as octal or hexadecimal digits. If string starts with a number from 1 to 9, parseInt() will parse it into a decimal integer.
Tips and Notes
Note: Only the first number in the string will be returned.
Note: Leading and trailing spaces are allowed.
Tip: If the first character of the string cannot be converted to a number, parseFloat() will return NaN.
Example
In this example, we will use parseInt() to parse different strings:
parseInt("10"); //Returns 10
parseInt("19",10); //Returns 19 ( 10+9)
parseInt("11",2); //Return 3 (2+1)
parseInt("17",8); //Return 15 (8+7)
parseInt("1f",16 ); //Return 31 (16+15)
parseInt("010"); //Undecided: return 10 or 8
parseInt("010",10); //Return 10
parseInt("0011",10) ;