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:
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:
function convertStoI() {
let a = "100";
let b = a * 1;
console.log(typeof (b));
let d = "3 11 43" * 1;
console.log(typeof (d));
}
convertStoI();
Output
number number
Method 2: Using the Number() function
The Number function is used to convert the parameter to the number type.
Example:
function convertStoI() {
const a = "100";
const b = Number(a);
console.log(typeof (b));
const d = "3 11 43" * 1;
console.log(typeof (d));
}
convertStoI();
Output
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.
function convertStoI() {
let a = "100";
let b = +(a);
console.log(typeof (b));
let d = +"3 11 43";
console.log(typeof (d));
}
convertStoI();
Output
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:
function convertStoI() {
let a = "100";
let b = Math.floor(a);
console.log(typeof (b));
}
convertStoI();
Output
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.
Example:
function convertStoI() {
let a = "100";
let b = Math.ceil(a);
console.log(typeof (b));
}
convertStoI();
Output
number
Method 6: Using Math.round() Function
The Math.round() function in JavaScript is used to round a number to the nearest integer. This method can also be used to convert a numeric string to an integer by rounding it to the nearest integer value.
Example:
function convertStoI() {
let a = "100.4";
let b = Math.round(a);
console.log(typeof (b));
}
convertStoI();
Output
number

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.
