Open In App

How to Convert String to Number in TypeScript?

Last Updated : 27 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In TypeScript, converting a string to a number is a common operation that can be accomplished using several different methods. Each method offers unique advantages and can be chosen based on the specific requirements of your application.

Below are the approaches to convert string to number in TypeScript:

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.

Example:  The following code demonstrates converting a string to a number by using the ‘+’ unary operator.

JavaScript
let str: string = "431";
console.log(typeof str);
let num = +str;
console.log(typeof num);

Output:

string
number

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.

Example: The following code demonstrates converting a string to a number by using the Number() method. Instead of using the ‘+’ operator, we can use the Number() function to convert string to number. The string must be given as an argument to the Number() function.

JavaScript
let str: string = "431";
console.log(typeof str);
let num = Number(str);
console.log(typeof num);

Output:

string
number

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.

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

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.

Example:

JavaScript
let str: string = "431";
console.log(typeof str);
let num = Number.parseInt(str);
console.log(typeof num);

Output:

string
number

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.

Example: In this example we are following above explained apporach.

JavaScript
let str: string = "431";
console.log(typeof str);

// Convert string to number using charCodeAt() and reduce()
let num = str.split('').reduce((acc, char) => acc * 10 + 
    (char.charCodeAt(0) - 48), 0);

console.log(typeof num);

Output:

string
number

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.

Example:

JavaScript
let str: string = "The price is $25.99";
console.log(typeof str);

// Extracting numerical values using regular expression
let num: number = parseFloat(str.match(/\d+\.\d+/)[0]);
console.log(`${num} is of type: ${typeof num}`);

Output:

25.99 is of type: number

Using the parseInt() Function with Radix

In this approach, we use the parseInt() function with a specified radix to convert a string to a number. The radix parameter specifies the base of the number in the string, allowing for conversions from various numeral systems (e.g., binary, octal, hexadecimal).

Example: Below is an example demonstrating the use of the parseInt() function with a radix to convert a string to a number in TypeScript.

JavaScript
let binaryString: string = "1101";
let binaryNumber: number = parseInt(binaryString, 2);
let octalString: string = "17";
let octalNumber: number = parseInt(octalString, 8);
let hexString: string = "1F";
let hexNumber: number = parseInt(hexString, 16);
console.log(`Binary string "${binaryString}" is converted to number:`, binaryNumber);
console.log(`Octal string "${octalString}" is converted to number:`, octalNumber);
console.log(`Hexadecimal string "${hexString}" is converted to number:`, hexNumber);

Output:

Binary string "1101" is converted to number: 13
Octal string "17" is converted to number: 15
Hexadecimal string "1F" is converted to number: 31


Next Article

Similar Reads