How to convert a string into a integer without using parseInt() function in JavaScript ?
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 the number which is present in any base to base 10 which is not possible using the method discusses above.
Example 1: The very simple idea is to multiply the string by 1. If the string contains a number it will convert to an integer otherwise NaN will be returned or we can type cast to Number.
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: 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
Please Login to comment...