Global parseInt() Function - Javascript Global

Javascript examples for Global:parseInt

Description

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

If the radix parameter is omitted, parseInt() would do the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). Deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

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 Description
stringRequired. The string to be parsed
radix Optional. A number (from 2 to 36) that represents the numeral system to be used

Return Value:

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

The following code shows how to Parse different strings:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {/* ww w  .j av  a 2  s  .  c om*/
    var a = parseInt("10") + "<br>";
    var b = parseInt("10.00") + "<br>";
    var c = parseInt("10.33") + "<br>";
    var d = parseInt("4 5 6") + "<br>";
    var e = parseInt("   6   ") + "<br>";
    var f = parseInt("4 years") + "<br>";
    var g = parseInt("it is 40") + "<br>";

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

    var n = a + b + c + d + e + f + g + "<br>" + h + i + j + k +l;
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

Related Tutorials