Convert String into Integer using Javascript

Script Sample

In this tutorial we will learn about converting String into Integer using Javascript. You can use the parseInt() function.

In this tutorial we will learn about converting String into Integer using Javascript. You can use the parseInt() function to parses a string and returns an Integer. The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from hexadecimal number to a decimal number. If the radix parameters is omitted, Javascript assumes the string begins with “0x” then the radix is 16 (hexadecimal), the string begins with “0” then the radix is 8 (octal) but this feature is already depcreated, and the string begins with any other value then the radix is 10 (decimal). The syntax and parameter values is describe in the below code.

Syntax

parseInt(string, radix)

 

Parameter Values

Parameter

Description

String

Required. The string to be parsed.

Radix

Optional. A number between 2 to 36 that represent the numeral system to be used.

 

Example: Convert String into Integer using Javascript

<!DOCTYPE html>
<html>
<body>

<p>Click the button to parse different strings.</p>

<button onclick="parseIntFunction()">Try it</button>

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

<script>
function parseIntFunction () {
  var a = parseInt("20") + "<br>";
  var b = parseInt("20.00") + "<br>";
  var c = parseInt("20.66") + "<br>";
  var d = parseInt("17 25 45") + "<br>";
  var e = parseInt("   30   ") + "<br>";
  var f = parseInt("20 years") + "<br>";
  var g = parseInt("He was 25") + "<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>

The output will be:

20
20
20
17
30
20
NaN

10
10
8
16
16

You cand find another javascript tutorial through this link.

Close