Last Updated : Jan 1, 2023
The parseInt() method parses a value as a string and returns the first integer.
It returns an integer given a string representation of decimal, binary, octal or hexadecimal numbers as input.
Here we defined two div element with id’s ‘res1,res2’ for append results on webpage.
In script we defined variable ‘a’ and stored value ‘10’ within double quotes we know when a decimal values specified within double quotes that will treated as string type in script so now variable had string value ‘10’.
We declared variable ‘b’ for store variable a’s value converted as integer value by parseInt() method.
<!DOCTYPE html> <html> <head> <title>STRING TO INT</title> </head> <body> <div id="res1"></div> <div id="res2"></div> <script> var a='10'; var b=parseInt(a); document.getElementById("res1").innerHTML="String is : "+a+" "+typeof(a); document.getElementById("res2").innerHTML="String Converted to Integer : "+b+" "+typeof(b); </script> </body> </html>
- <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in and it’s not have any ending tag.
- The<html> tag is used to indicate the beginning of HTML document.
- As above shown <head> tag is contain information about webpage and external file links are declared here. <title> tag is used for set the webpage title.
- Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If you’re not closed anyone of ending tag properly that is also affect the webpage result.
- <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here.
- Here we defined two div elements with id’s ‘res1,res2’ for appends result on webpage by innerHTML.
- In script variable ‘a’ defined for store string type value ‘10’ then we passing variable a to parseInt() method as parameter for convert string to integer type.
- Then converted result value stored on variable ‘b’ and then finally we printed result on webpage’s div element ‘res1,res2’ by innerHTML.
- If you wish to change string ‘10’ to some other value you can modify it result will be same.
- Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.
Using typeOf() method we printed their original type in result for user clarification and without type result we can’t easily figure out the result that’s way we specified them.
We can also convert any types like octal or hexadecimal into integer type by using this method.