Convert the string to a integer in JavaScript
In this tutorial, we are going to learn about how to convert a string to a integer in JavaScript with the help of examples.
Consider, we have a following numeric string:
a = "25";
Now, we need to convert the above string to a integer like this: “25” to 25 .
Using + Plus Operator
To convert a string to a integer, we can use the + operator in JavaScript.
Here is an example:
const a = "25";
const result = +a;
console.log(result);
Output:
25
In the above code, we have added the +
plus operator infront of a string. so that it will converts the string to a number.
Using Number() method
Alternatively, we can also use the built-in Number()
method in JavaScript to convert a numeric string into a integer.
The Number()
method accepts the string as an argument and returns the integer.
Here is an example:
const a = "25";
const result = Number(a);
console.log(result); // 25
Using Number.parseInt() method
The Number.parseInt()
takes the two arguments, the first argument is a string and the second argument is the base of a required number that should be converted.
Here is an example:
const a = "25";
const result = Number.parseInt(a, 10);
console.log(result); // 25
In the above code, we have passed the base 10 as a second argument to the Number.parseInt() method.So it parses the string a returns the of base 10.
Note: Base 10 is used for decimal numbers.
Additional resources
You can also checkout similar tutorials by reading the following: