Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Convert String to Boolean in TypeScript ?
Next article icon

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:

Table of Content

  • Using the ‘+’ unary operator
  • Using Number() method
  • Using parseFloat() function
  • Using Number.parseInt()
  • Using String.prototype.charCodeAt() and Array.prototype.reduce()
  • Using Regular Expressions
  • Using the parseInt() Function with Radix

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
How to Convert String to Boolean in TypeScript ?

S

sarahjane3102
Improve
Article Tags :
  • JavaScript
  • TypeScript
  • Web Technologies
  • TypeScript-Questions

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences