Convert a String to an Integer in JavaScript
These are the following ways to convert string to an integer in JavaScript:
1. Using Number() Method
The number() method converts a string into an integer number. It works similarly to the unary plus operator.
let s = "100.45";
console.log(typeof Number(s));
Output
number
2. Using Unary + Operator
The Unary + Operator is a quick and concise way to convert strings to numbers. It attempts to convert the operand to a number and is often used for this purpose.
let s1 = "23";
let s2 = "Manya";
const s3 = '100';
console.log(
typeof +s1,typeof +s2, typeof +s3
);
Output
number number number
3. Using parseInt() Method
The parseInt() method parses a string and returns an integer value of the specified radix (base). If radix is not specified, it takes default value 10 (decimal).
let s = "100.45";
console.log(typeof parseInt(s));
Output
number
4. Using Math.floor() Method
The Math.floor() method can be used to convert a string into a number. This method round off to down the number after converting from string.
let s = "101.45";
let n = Math.floor(parseFloat(s));
console.log(typeof n);
Output
number
5. Using Bitwise Operator
The Bitwise Operators like | 0 or << 0 can also perform string-to-integer conversion in a concise manner.
let s = "101.45";
let n = s | 0;
console.log(typeof n);
Output
number
6. Using Math.round() Method
The math.round() method can also be used to convert string to number in JavaScript. It rounds the number to specified decimal places.
let s = "101.45";
let n = Math.round(s);
console.log(typeof n);
Output
number
7. Using BigInt() Constructor
The BigInt() constructor can be used to convert a string into a BigInt integer. This is particularly useful when dealing with very large integers that exceed the maximum safe integer limit in JavaScript.
// Using BigInt() constructor to convert
// a string into a BigInt integer
let s = "12345678901234567890";
let n = BigInt(s);
console.log("Type Before Conversion: " + typeof s);
console.log("Type After Conversion: " + typeof n);
Output
Type Before Conversion: string Type After Conversion: bigint
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.