How to Convert the string to a number in Node.js
In this tutorial, we are going to learn about how to convert the string to a number in Node.js with the help of examples.
Consider, we have a following numeric string:
a = "25";
Now, we need to convert the above string to a number like this: “25” to 25 .
Using + Plus Operator
To convert a string to a number, we can use the plus +
operator in Node.js.
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 Node.js to convert a numeric string into a number.
The Number()
method accepts the string as an argument and returns the number.
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: