parseInt() function with example in JavaScript

JavaScript parseInt() function: Here, we are going to learn about the parseInt() function with example in JavaScript.
Submitted by IncludeHelp, on February 01, 2019

The function parseInt() is used to convert a string to the integer or we can say it can be used to parse a string and returns an integer.

Some of the points to remember:

  • If a string contains number at the starting it can parse and returns the number.
  • If a string contains alphabets at the starting and then the number, it cannot parse and returns "NaN".
  • If a string contains leading and trailing spaces still function works and parse the string.
  • As we have discussed in the post convert hexadecimal string to the decimalparseInt() function parses the octal formatted value by passing base 8 and hexadecimal value by passing base 16 to the number.

Example:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var str1 = "123";	//decoimal string
		var str2 = "12.23";	//float string
		var str3 = "123 456 789" //multiple Numbers 
		var str4 = "  123  "; //string contains leading & trailing spaces
		var str5 = "012" ; //octal string
		var str6 = "0x0A"; //hexadecimal string
		var str7 = "123456 is my password"; //string contains Number in starting
		var str8 = "My password is 123456"; //string contains Number in ending
		
		//parsing & pritning the values
		document.write("Number value of str1: " + parseInt(str1) + "<br>");
		document.write("Number value of str2: " + parseInt(str2) + "<br>");
		document.write("Number value of str3: " + parseInt(str3) + "<br>");
		document.write("Number value of str4: " + parseInt(str4) + "<br>");
		document.write("Number value of str5: " + parseInt(str5,8) + "<br>");
		document.write("Number value of str6: " + parseInt(str6,16) + "<br>");
		document.write("Number value of str7: " + parseInt(str7) + "<br>");
		document.write("Number value of str8: " + parseInt(str8) + "<br>");
	</script>
</body>
</html>

Output

Number value of str1: 123
Number value of str2: 12
Number value of str3: 123
Number value of str4: 123
Number value of str5: 10
Number value of str6: 10
Number value of str7: 123456
Number value of str8: NaN

JavaScript Built-in Functions »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.