/

HTML / CSS / JavaScript Tutorial

JavaScript Global method: parseInt()

[this page | pdf | back links]

The JavaScript Global parseInt() method parses a string returns an integer where practical. If the first available non-space character of x is not numerical then the method returns NaN. Only the first of multiple numbers will be returned.

 

It has the following syntax with the following parameters:

 

parseInt(x, radix)

 

Parameter

Required / Optional

Description

x

Required

String corresponding to the input number

radix

Optional

An integer between 2 and 36 specifying the radix, i.e. number base, used in forming the integer from the strong. See below if omitted

 

Users are recommended to include a radix as the results can otherwise vary by browser. Usually, if the radix is omitted and x begins with “0x” (maybe “Ox”) then the radix (number base) is taken to be 16. If it begins with “0” (maybe “O”) then the radix is base 8 (this option is depreciated), otherwise usually the radix is defaulted to base 10 (i.e. decimal). The method finds the first character in x after leading spaces, works out if this is one that can appear in a number and then continues parsing the string until it reaches the end of any part that is interpretable as a number, returning that number as a number value, not a string.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse :collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
<tr>
<td><code id="Example2"></code></td>
<td><code id="Result2"></code></td>
</tr>
</table>

<script>
document.getElementById("Example").innerHTML =
  'var x = parseInt("   3, 4");';
document.getElementById("Result").innerHTML =
  parseFloat("   3, 4");
document.getElementById("Example2").innerHTML =
  'var x2 = parseFloat("   a3, 4");';
document.getElementById("Result2").innerHTML =
  parseFloat("   a3, 4");
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodGlobalParseInt() {
  return (parseInt("3") == 3);
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile