How to Convert String to Number in TypeScript?
Last Updated :
27 Aug, 2024
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
Similar Reads
How to Convert Number to String in TypeScript ?
Converting floats to strings is a common operation in programming that enables us to work with numeric data in a more flexible and controlled manner. Below are the approaches: Table of Content Using toString() MethodUsing Template LiteralsUsing toFixed() MethodUsing String ConstructorUsing toLocaleS
4 min read
How to Convert String to Date in TypeScript ?
In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC. Table of Content Using new Date()Using Date.parse() Using Date.UTC()Using new Date()In this appro
2 min read
How to Convert String to Number
Given a string representation of a numerical value, convert it into an actual numerical value. In this article, we will provide a detailed overview about different ways to convert string to number in different languages. Table of Content Convert String to Number in CConvert String to Number in C++Co
5 min read
How to Restrict a Number to a Certain Range in TypeScript ?
Restricting a number to a certain range in TypeScript means ensuring that a numerical value falls within specific bounds or limits. This process, often referred to as "clamping" or "bounding," prevents a number from going below a minimum value or exceeding a maximum value. For example, if you have a
2 min read
How to Format Strings in TypeScript ?
Formatting strings in TypeScript involves combining and structuring text to produce clear and readable output. This practice is essential for creating dynamic and user-friendly applications, as it allows developers to seamlessly integrate variables and expressions into strings, enhancing the overall
3 min read
How to Convert string to integer type in Golang?
Strings in Golang is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go language, both signed and unsigned integers are available in four different sizes. In order to convert string to integer type in Golang, you can
2 min read
How to Sort a Numerical String in TypeScript ?
To sort numerical string in TypeScript, we could use localCompare method or convert numerical string to number. Below are the approaches used to sort numerical string in TypeScript: Table of Content Using localeCompareConverting to Numbers before sortingApproach 1: Using localeCompareThe localeCompa
2 min read
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a paramet
4 min read
How to Define a Regex-Matched String Type in TypeScript ?
Defining a regex-matched string type in TypeScript means creating a type that ensures a string adheres to a specific regular expression pattern. This enhances type safety by validating strings at compile or runtime, ensuring they match predefined formats. What is a Regex-Matched String?A "regex-matc
4 min read
How to convert string into a number using AngularJS ?
In this article, we will see how to convert a string into a number in AngularJS, along with understanding its implementation through the illustrations. Approach: The parseInt() method is used for converting the string to an integer. We will check whether the string is an integer or not by the isNumb
2 min read