Javascript - Global parseInt() Function

The parseInt() function parses a string and returns an integer.

Description

The parseInt() function parses a string and returns an integer.

The radix parameter sets which numeral system to be used.

A radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

  • 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)

Only the first number in the string is returned!

Leading and trailing spaces are allowed.

If the first character cannot be converted to a number, parseInt() returns NaN.

Syntax

parseInt(string, radix)

Parameter Values

Parameter Require Description
stringRequired. The string to be parsed
radix Optional. A number (from 2 to 36) that represents the numeral system to be used

Return

A Number. If the first character cannot be converted to a number, NaN is returned

Example

Parse different strings:

Demo

var a = parseInt("10") + "\n";
var b = parseInt("10.00") + "\n";
var c = parseInt("10.33") + "\n";
var d = parseInt("3 5 6") + "\n";
var e = parseInt("   60   ") + "\n";
var f = parseInt("40 years") + "\n";
var g = parseInt("this is 40") + "\n";

var h = parseInt("10", 10)+ "\n";
var i = parseInt("010")+ "\n";
var j = parseInt("10", 8)+ "\n";
var k = parseInt("0x10")+ "\n";
var l = parseInt("10", 16)+ "\n";

var n = a + b + c + d + e + f + g + "\n" + h + i + j + k +l;
console.log(n);/*from  www . j  a va2 s . c o  m*/

Result