parses the string to create an integer value
Description
parseInt()
function examines the string
to see if it matches a number pattern.
parseInt()
uses the following rules to convert string to an integer.
- The
parseInt()
function ignores leading white space and it checks the string character by character. - If this first non-white space character isn't a number,
the minus sign, or the plus sign,
parseInt()
returnsNaN
. - The
parseInt()
function returnsNaN
for empty string, whileNumber()
function returns0
. - If the first character is a number, plus, or minus,
then the checking continues until the end of the string is reached
or a non numeric character is found.
For instance, "
1234asdf
" is converted to1234
because "asdf
" is ignored. - When the string begins with "0x", it is interpreted as a hexadecimal integer.
- If a string begins with "0" followed by a number, it is interpreted as an octal value.
Example
var num1 = parseInt("1234blue"); //1234
console.log(num1);/*from w ww. j av a 2 s .c om*/
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.
radix
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);// w ww.ja v a 2 s. c om
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);