The parseInt()
function parses a string and returns an integer.
parseInt()
function examines the string
to see if it matches a number pattern.
parseInt()
uses the following rules to convert string to an integer.
parseInt()
function ignores
leading white space and it checks the string character by character.parseInt()
returns NaN
.parseInt()
function returns NaN
for
empty string, while Number()
function returns 0
.1234asdf
" is converted to 1234
because "asdf
"
is ignored.parseInt |
Yes | Yes | Yes | Yes | Yes |
parseInt(string, radix)
Parameter | Description |
---|---|
string | Required. The string to be parsed |
radix | Optional. A number from 2 to 36 that represents the numeral system to be used |
A Number type value. If the first character cannot be converted to a number, NaN is returned.
var num1 = parseInt("1234blue"); //1234
console.log(num1);// w ww. ja v a 2s . com
var num2 = parseInt(""); //NaN
console.log(num2);
var num3 = parseInt("0xA"); //10 - hexadecimal
console.log(num3);
var num4 = parseInt(22.5); //22
console.log(num4);
var num5 = parseInt("70"); //70 - decimal
console.log(num5);
var num6 = parseInt("0xf"); //15 - hexadecimal
console.log(num6);
//56 (octal) in ECMAScript 3, 0 (decimal) in ECMAScript 5
var num = parseInt("070");
console.log(num);
The code above generates the following result.
parseInt()
provides a second argument: the radix.
For hexadecimal format, the radix is 16.
console.log(parseInt("0xAE", 16));
The code above generates the following result.
The leading "0x" is not necessary by providing the hexadecimal radix:
console.log(parseInt("AE", 16)); var num2 = parseInt("AF"); //NaN console.log(num2);
The code above generates the following result.
Most of the time you'll be parsing decimal numbers, so it's good to always include 10 as the second argument.
var num1 = parseInt("10", 2); //2 - parsed as binary console.log(num1); var num2 = parseInt("10", 8); //8 - parsed as octal console.log(num2); var num3 = parseInt("10", 10); //10 - parsed as decimal console.log(num3); var num4 = parseInt("10", 16); //16 - parsed as hexadecimal console.log(num4);