In typescript, there are numerous ways to convert a string to a number. We can use the ‘+’ unary operator , Number(), parseInt() or parseFloat() function to convert string to number. Let’s demonstrate using a few examples.
Example 1: The following code demonstrates converting a string to a number by using the ‘+’ unary operator.
let str: string = "431" ;
console.log( typeof str);
let num = +str; console.log( typeof num);
|
Output:
string number
Example 2: The following code demonstrates converting a string to a number by using the Number() method. Instead of using the ‘+’ operator, we can use the Number() function to convert string to number. The string must be given as an argument to the Number() function.
let str: string = "431" ;
console.log( typeof str);
let num = Number(str); console.log( typeof num);
|
Output:
string number
Example 3: Numbers can be of type float or int. To convert a string in the form of float to a number we use the parseFloat() function and to convert strings that do not have decimal to a number, the parseInt() function is used.
let str1:string = "102.2" ;
console.log( typeof str1);
let num = parseFloat(str1); console.log(`${num}` + " is of type :" + typeof num);
let str2:string = "61" ;
console.log( typeof str2);
let num2 = parseInt(str2); console.log(`${num2}` + " is of type :" + typeof num2);
|
Output:
string 102.2 is of type :number string 61 is of type :number