Convert a string to an integer in JavaScript
In JavaScript parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function.
parseInt() function returns Nan( not a number) when the string doesn’t contain number.
Syntax:
parseInt(Value, radix)
It accepts string as a value and converts it to specified radix system and returns an integer.
Program to convert string to integer:
Example-1:
<script> function convertStoI() { var a = "100" ; var b = parseInt(a); document.write( "Integer value is" + b); var d = parseInt( "3 11 43" ); document.write( "</br>" ); document.write( 'Integer value is ' + d); } convertStoI(); </script> |
Output:
Integer value is100 Integer value is 3
ParseInt() function converts number which is present in any base to base 10. It parses string and converts until it faces a string literal and stops parsing.
Example-2:
<script> function convertStoI() { var r = parseInt( "1011" , 2); var k = parseInt( "234" , 8); document.write( 'Integer value is ' + r); document.write( "<br>" ); document.write( "integer value is " + k); document.write( "<br>" ); document.write(parseInt( "528GeeksforGeeks" )); } convertStoI(); </script> |
Output:
Integer value is 11 integer value is 156 528
Recommended Posts:
- Convert boolean result into number/integer in JavaScript
- How to convert string into float in JavaScript?
- JavaScript | Convert a string to boolean
- Convert string into date using JavaScript
- How to convert an object to string using JavaScript?
- Convert string to title case in JavaScript
- How to convert string to camel case in JavaScript ?
- How to convert seconds to time string format hh:mm:ss using JavaScript ?
- How to Convert JS Object to JSON String in JQuery/Javascript?
- Convert comma separated string to array using JavaScript
- JavaScript | Convert bytes to human-readable string
- How to convert a currency string to a double value with jQuery or Javascript?
- Find quotient and remainder by dividing an integer in JavaScript
- How to convert decimal to hex in JavaScript ?
- How to convert a JavaScript date to UTC?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.