Skip to content
Related Articles

Related Articles

Convert a string to an integer in JavaScript

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 25 May, 2022

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 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 (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: 

javascript




<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: 

javascript




<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

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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!