How to Convert a String to an Integer in JavaScript

By FoxLearn 9/6/2024 1:50:03 AM   133
In JavaScript, there are several ways to convert a string to an integer.

How do I convert a string to an integer in JavaScript?

1. Using parseInt() to convert string to int

The parseInt() function parses a string and returns an integer.

For example:

let str = "1234";
let num = parseInt(str, 10); // 10 is the radix for decimal numbers
console.log(num); // 1234

It also allows you to specify the radix (base) of the number system.

2. Using the Unary Plus Operator (+) to convert string to int

If your string is already in the form of an integer, you can use unary plus operator to convert to integer.

For example:

let str = "1234";
let num = +str;
console.log(num); // 1234

The unary plus operator is a quick and concise way to convert a string to a number.

3. Using the Number() Function to convert string to int

The Number() function converts a value to a number.

For example:

let str = "1234";
let num = Number(str);
console.log(num); // 1234

4. Using Math.floor(), Math.ceil(), or Math.round() to convert string to int

If you need to ensure that the result is an integer, you can use the functions below.

For example:

let str = "1234.43";
let num = Math.floor(Number(str)); // Converts to 1234
console.log(num);

num = Math.ceil(Number(str)); // Converts to 1235
console.log(num);

num = Math.round(Number(str)); // Converts to 1234
console.log(num);

If the string cannot be converted to an integer (e.g., "abcd"), parseInt() will return NaN (Not-a-Number). Similarly, Number() will also return NaN for non-numeric strings.

The unary plus operator and Number() function handle floating-point numbers as well. If you specifically need an integer, you might need to use additional methods like Math.floor(), Math.ceil(), or Math.round().