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 an 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.
Below are the following methods:
- Using coercion
- Using the Number() function
- Using the unary + operator
- Using Math floor() Method
- Using Math.ceil( ) function
Method 1: Using coercion
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.
Example:
Javascript
function convertStoI() { let a = "100" ; let b = a * 1; console.log( typeof (b)); let d = "3 11 43" * 1; console.log( typeof (d)); } convertStoI(); |
number number
Method 2: Using the Number() function
The Number function is used to convert the parameter to the number type.
Example:
Javascript
function convertStoI() { const a = "100" ; const b = Number(a); console.log( typeof (b)); const d = "3 11 43" * 1; console.log( typeof (d)); } convertStoI(); |
number number
Method 3: Using the unary + operator
If we use the ‘+’ operator before any string if the string in numeric it converts it to a number.
Javascript
function convertStoI() { let a = "100" ; let b = +(a); console.log( typeof (b)); let d = + "3 11 43" ; console.log( typeof (d)); } convertStoI(); |
number number
Method 4: Using Math floor() Method
The Javascript Math.floor() method is used to round off the number passed as a parameter to its nearest integer in a Downward direction of rounding i.e. towards the lesser value.
Example:
Javascript
function convertStoI() { let a = "100" ; let b = Math.floor(a); console.log( typeof (b)); } convertStoI(); |
number
Method 5: Using Math.ceil( ) function
The Math.ceil() function in JavaScript is used to round the number passed as a parameter to its nearest integer in an Upward direction of rounding i.e. towards the greater value.
Javascript
function convertStoI() { let a = "100" ; let b = Math.ceil(a); console.log( typeof (b)); } convertStoI(); |
number