How to Convert a String to Number in TypeScript

Here are three ways to convert a string to a number in TypeScript:

  1. Using unary + operator
  2. Using parseFloat()/parseInt()
  3. Using Number()

Method 1: Using (+) operator

The unary + operator is used to convert a string to a number. When used with a string representing a valid number, it converts the string to that number. If the string cannot be converted, it returns NaN.

const stringValue: string = "42";
const numericValue: number = +stringValue;

console.log(numericValue);

Output

42

Method 2: Using parseFloat()/parseInt() function

The parseFloat() function “takes a string as input and tries to parse it as a floating-point number”. If successful, it returns the number; otherwise, it returns NaN.

const stringValue: string = "42.5";
const floatValue: number = parseFloat(stringValue);
console.log(floatValue);

const intValue: number = parseInt(stringValue, 10);
console.log(intValue);

Output

42.5
42

Method 3: Using Number() constructor

The Number() constructor function takes a value as input and attempts to convert it to a number. If the conversion is successful, it returns the number. If the input cannot be converted to a number, it returns NaN (Not a Number). It works with both integers and floating-point numbers.

var stringValue = "42";
var numericValue = Number(stringValue);

console.log(numericValue);

Output

42

That’s it.