Convert the string to a number in TypeScript
In this tutorial, we are going to learn how to convert a string to a number in TypeScript 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 + operator in TypeScript.
Here is an example:
const a:string = "25";
const result:number = +a;
console.log(result);
Output:
25
In the above code, we have added the +
plus operator infront of a string. so TypeScript converts the string to a number.
Using Number() method
Alternatively, we can also use the built-in Number()
method in TypeScript to convert a numeric string into a number.
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: