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 String to JSON in TypeScript ?
Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript: Table of Content Convert String to JSON Using JSON.parse()Convert String
6 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 a String to enum in TypeScript?
In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript. These are the two approaches that can be used to solve it: Table of Content
5 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do. Table of Content Using JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsi
5 min read
How to Convert String to Boolean in TypeScript ?
In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it. There are several approaches to convert string to boolean in TypeScript which are as follows: Table of Content Using Conditional StatementUsing JSON.parse() MethodU
4 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 Convert Map to JSON in TypeScript ?
In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion. Table of Content Using JSON.stringifyUsing fast-json-
5 min read
How to Convert a Bool to String Value in TypeScript ?
When we talk about converting a boolean to a string value in TypeScript, we mean changing the data type of a variable from a boolean (true or false) to a string (a sequence of characters). We have multiple approaches to convert a bool to a string value in TypeScript. Example: let's say you have a va
4 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 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