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);
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);
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);