Convert a string to an integer in JavaScript
In this article, we will convert a string into an integer in Javascript. In JavaScript parseInt() function (or a method) is used to convert the passed-in string parameter or value to an integer value itself. This function returns an integer of the base which is specified in the second argument of the parseInt() function. JavaScript parseInt() function returns Nan( not a number) when the string doesn’t contain a number.
Syntax:
parseInt(Value, radix)
Parameters: It accepts a string as a value and converts it to a specified radix system (any desired numerical value passed by a user) and returns an integer (corresponding to the passed in numerical radix value).
Program to convert string to integer:
Example 1: In this example, we will convert a string value to an integer using the parseInt() function with no second parameter.
javascript
<script> function convertStoI() { var a = "100" ; var b = parseInt(a); console.log( "Integer value is" + b); var d = parseInt( "3 11 43" ); console.log( 'Integer value is ' + d); } convertStoI(); </script> |
Output:
Integer value is 100 Integer value is 3
JavaScript ParseInt() function converts the 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: In this example, we will convert a string value to an integer using the parseInt() function with a second parameter.
javascript
<script> function convertStoI() { var r = parseInt( "1011" , 2); var k = parseInt( "234" , 8); console.log( 'Integer value is ' + r); console.log( "integer value is " + k); console.log(parseInt( "528GeeksforGeeks" )); } convertStoI(); </script> |
Output:
Integer value is 11 integer value is 156 528
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Please Login to comment...