How to use parseFloat() function In Typescript
The parseFloat() function in TypeScript converts a string to a floating-point number by parsing its content. It extracts and interprets the numerical portion of the string, ensuring type conversion.
Example : 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
How to convert string to number in TypeScript ?
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.
Table of Content
- Using the ‘+’ unary operator
- Using Number() method
- Using parseFloat() function
- Using Number.parseInt()
- Using String.prototype.charCodeAt() and Array.prototype.reduce()
- Using Regular Expressions