How to Convert a String to Number in TypeScript

To convert a string to a number in TypeScript, you can use the “Number() constructor”, “parseFloat()/parseInt() function“, or “unary + operator”.

Method 1: Using the 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

Method 2: Using the 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.

The parseInt() function is similar but parses the input string as an integer. It takes two arguments: the string to be parsed and the radix (base) of the number system to be used. For decimal numbers, you should use a radix of 10.

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 the (+) operator

The unary + operator tries to convert its operand 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

These methods work in TypeScript, as TypeScript is a superset of JavaScript and shares the same runtime behavior. Choose the method that best suits your use case and coding style.

Leave a Comment