Use parseInt() to convert string to an integer

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() returns NaN.
  • The parseInt() function returns NaN for empty string, while Number() function returns 0.
  • 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 to 1234 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 w w . j  a v  a  2  s .  co m*/
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.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions