Here are three ways to convert a string to a number in TypeScript:
- Using unary + operator
- Using parseFloat()/parseInt()
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.