In JavaScript, a string can be converted into an integer without using the parseInt() function by manually processing each character. This method involves converting each digit character into its numeric value and building the final integer step by step.
- It works by iterating through each character of the string and converting it to its corresponding number.
- The result is calculated using mathematical operations (multiply by 10 and add the digit).
- This method only works for base-10 numeric strings and requires extra logic to handle negative numbers or invalid characters.
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.
function convertStoI() {
let a = "100";
let b = a * 1;
console.log(typeof (b));
let d = "3 11 43" * 1;
console.log(typeof (d));
}
convertStoI();
Method 2: Using the Number() function
The Number function is used to convert the parameter to the number type.
function convertStoI() {
const a = "100";
const b = Number(a);
console.log(typeof (b));
const d = "3 11 43" * 1;
console.log(typeof (d));
}
convertStoI();
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();
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.
function convertStoI() {
let a = "100";
let b = Math.floor(a);
console.log(typeof (b));
}
convertStoI();
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.
function convertStoI() {
let a = "100";
let b = Math.ceil(a);
console.log(typeof (b));
}
convertStoI();
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.
function convertStoI() {
let a = "100.4";
let b = Math.round(a);
console.log(typeof (b));
}
convertStoI();