January 13, 2016
String to Integer Conversion in JavaScript
We have seen in previous tutorial that JavaScript treat a number as a string if you assign it using quotation marks. Instead of addition of 2 numbers, it will perform concatenation. To overcome this issue, we make use of parseInt() function in JavaScript. This function will convert string to integer. Example is given below.
Note: If you try to retrieve a value within textbox using JavaScript, then that value will also be treated as a string. So, you have to perform string to integer conversion to do calculation.
<html> <head> <title>JavaScript Tutorial </title> </head> <body> <script type="text/javascript"> var n1 = "10"; var n2 = "30"; var total = n1+n2; var sum = parseInt(n1) + parseInt(n2); //Total = 1030 alert(total); //Sum = 40 alert(sum); </script> </body> </html>