Given a number in form of string, the task is to convert the given string to an Integer in JavaScript. It is mostly useful for very large number.
Approach 1: Using parseInt() Method
The parseInt()
function is the most commonly used method to convert a string to an integer in JavaScript. It parses a string argument and returns an integer of the specified radix (base).
const stringNumber = "123"; const integerValue = parseInt(stringNumber, 10); console.log(integerValue); // Output: 123
Approach 2: Using Number() Function
The Number()
function is another built-in method to convert a string to an integer in JavaScript. It attempts to convert the argument to a number.
const stringNumber = "123"; const integerValue = Number(stringNumber); console.log(integerValue); // Output: 123
Approach 3: Using Unary Plus Operator (+)
The unary plus operator (+
) can also be used to convert a string to an integer. It converts the string representation of a number into a number.
const stringNumber = "123"; const integerValue = +stringNumber; console.log(integerValue); // Output: 123
Approach 4: Using Bitwise Operators
You can use bitwise operators like | 0
or >> 0
to convert a string to an integer. These operators implicitly convert their operands to 32-bit integers.
const stringNumber = "123"; const integerValue = stringNumber | 0; console.log(integerValue); // Output: 123
Approach 5: Using Math.floor() Method
While not as common, you can also use the Math.floor()
function to convert a string to an integer. This method effectively truncates any decimal part of the number.
const stringNumber = "123"; const integerValue = Math.floor(stringNumber); console.log(integerValue); // Output: 123
Approach 6: Using Unary Bitwise NOT Operator (~)
Another unconventional method is to use the unary bitwise NOT operator (~
) followed by the bitwise NOT operator itself. This method is not recommended for general use due to its complexity and potential side effects.
const stringNumber = "123"; const integerValue = ~~stringNumber; console.log(integerValue); // Output: 123