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. 

Javascript
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

Similar Reads

1. Using the ‘+’ unary operator

The unary plus operator (`+`) in TypeScript converts a string to a number by parsing its content. It coerces the string representation of numeric characters into a numerical value, ensuring type conversion....

2. Using Number() method

The Number() method in TypeScript converts a string to a number by explicitly invoking the Number constructor. It parses the string’s content to a numerical value, ensuring type conversion....

3. Using parseFloat() function

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....

4. Using Number.parseInt()

The Number.parseInt() method parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). It’s particularly useful when you want to convert a string to an integer, optionally with a specified radix....

5. Using String.prototype.charCodeAt() and Array.prototype.reduce()

We can leverage the charCodeAt() method along with the reduce() method of arrays to convert a string representing a numeric value to a number in TypeScript. This approach involves converting each character of the string to its Unicode code point and then reconstructing the numeric value based on these code points....

6. Using Regular Expressions

Regular expressions provide a powerful tool for pattern matching and manipulation in TypeScript. By leveraging regular expressions, we can extract numerical values from strings and convert them to numbers....