Skip to content
Related Articles

Related Articles

How to convert a string into a integer without using parseInt() function in JavaScript ?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 27 Jul, 2022
View Discussion
Improve Article
Save Article

In JavaScript, there is a simple function parseInt() to convert a string to an integer. In order to know more about the function, you can refer to this. In this article, we will learn how to convert the string to integer without using the parseInt() function. Advantage of parseInt() over this method. The parseInt() function converts number which is present in any base to base 10 which is not possible using the method discusses above.

The very simple idea is to multiply the string with 1. If the string contains a number it will convert to an integer otherwise NaN will be returned

Example 1:

Javascript




<script>
        function convertStoI() {
        var a = "100";
        var b = a*1;
        console.log(typeof(b));
        var d = "3 11 43"*1;
        console.log(typeof(d));
    }
convertStoI();
</script>   

Output:

number
number

Example 2:

Javascript




</script>   
function convertStoI() {
      // The second argument specifies
      // the number passes is in base 2
       
      var r = parseInt("111", 2); 
           console.log('Integer value is ' + r);
         
      // The second argument specifies
      // the number passes is in base 8
      var p = parseInt("156", 8); 
           console.log('Integer value is ' + p);
         
      // The second argument specifies
      // the number passes is in base 16
      var q = parseInt("AE", 16); 
           console.log('Integer value is ' + q);
         
        
    }
convertStoI();
</script>

Output:

Integer value is 7
Integer value is 110
Integer value is 174

Method#2: Using Number() function: The Number function is used to convert the parameter to number type.

Javascript




<script>
        function convertStoI() {
            var a = "100";
            var b = Number(a);
            console.log(typeof(b));
            var d = "3 11 43"*1;
            console.log(typeof(d));
    }
convertStoI();
 
</script>

Output:

number
number

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!