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
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to Convert Number to String
Next article icon

How to Convert String to Number

Last Updated : 28 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 C
  • Convert String to Number in C++
  • Convert String to Number in Java
  • Convert String to Number in Python
  • Convert String to Number in C#
  • Convert String to Number in JavaScript

Convert String to Number in C:

1. Using Built-in Functions:

  • Use the built-in function to convert the string to a number.
C
#include <stdio.h> #include <stdlib.h>  int main() {     char str[] = "123";      // Step 1     int num = atoi(str);      printf("%d\n", num);     return 0; } 

Output
123 

2. String Concatenation:

  • Check if the string represents a negative number and set a flag.
  • Iterate over each character of the string and convert it to its corresponding numerical value.
  • Calculate the numerical value using the digits.
C
#include <stdio.h>  int main() {     char str[] = "-123";     int i = 0, sign = 1, num = 0;      // Step 1     if (str[0] == '-') {         sign = -1;         i++;     }      // Step 2     while (str[i] != '\0') {         num = num * 10 + (str[i] - '0');         i++;     }      // Step 3     num *= sign;      printf("%d\n", num);     return 0; } 

Output
-123 

Convert String to Number in C++:

1. Using Built-in Functions:

  • Use the built-in function to convert the string to a number.
C++
#include <iostream> #include <string> using namespace std;  int main() {     string str = "123";      // Step 1     int num = stoi(str);      cout << num << endl;     return 0; } 

Output
123 

2. String Concatenation:

  • Check if the string represents a negative number and set a flag.
  • Iterate over each character of the string and convert it to its corresponding numerical value.
  • Calculate the numerical value using the digits.
C++
#include <iostream> #include <string> using namespace std;  int main() {     string str = "-123";     int sign = 1, num = 0;      // Step 1     if (str[0] == '-') {         sign = -1;         str = str.substr(1);     }      // Step 2     for (char c : str) {         num = num * 10 + (c - '0');     }      // Step 3     num *= sign;      cout << num << endl;     return 0; } 

Output
-123 

Convert String to Number in Java:

1. Using Built-in Functions:

  • Use the built-in function to convert the string to a number.
Java
public class Main {     public static void main(String[] args)     {         String str = "123";          // Step 1         int num = Integer.parseInt(str);          System.out.println(num);     } } 

Output
123 

2. String Concatenation:

  • Check if the string represents a negative number and set a flag.
  • Iterate over each character of the string and convert it to its corresponding numerical value.
  • Calculate the numerical value using the digits.
Java
public class Main {     public static void main(String[] args)     {         String str = "-123";         int sign = 1, num = 0;          // Step 1         if (str.charAt(0) == '-') {             sign = -1;             str = str.substring(1);         }          // Step 2         for (char c : str.toCharArray()) {             num = num * 10 + (c - '0');         }          // Step 3         num *= sign;          System.out.println(num);     } } 

Output
-123 

Convert String to Number in Python:

1. Using Built-in Functions:

  • Use the built-in function to convert the string to a number.
Python
str_num = "123"  # Step 1 num = int(str_num)  print(num) 

Output
123 

2. String Concatenation:

  • Check if the string represents a negative number and set a flag.
  • Iterate over each character of the string and convert it to its corresponding numerical value.
  • Calculate the numerical value using the digits.
Python
str_num = "-123" sign = 1 num = 0  # Step 1 if str_num[0] == '-':     sign = -1     str_num = str_num[1:]  # Step 2 for c in str_num:     num = num * 10 + int(c)  # Step 3 num *= sign  print(num) 

Output
-123 

Convert String to Number in C#:

1. Using Built-in Functions:

  • Use the built-in function to convert the string to a number.
C#
using System;  class Program {     static void Main()     {         string str = "123";          // Step 1         int num = int.Parse(str);          Console.WriteLine(num);     } } 

Output
123 

2. String Concatenation:

  • Check if the string represents a negative number and set a flag.
  • Iterate over each character of the string and convert it to its corresponding numerical value.
  • Calculate the numerical value using the digits.
C#
using System;  class Program {     static void Main()     {         string str = "-123";         int sign = 1, num = 0;          // Step 1         if (str[0] == '-')         {             sign = -1;             str = str.Substring(1);         }          // Step 2         foreach (char c in str)         {             num = num * 10 + (c - '0');         }          // Step 3         num *= sign;          Console.WriteLine(num);     } } 

Output
-123 

Convert String to Number in JavaScript:

1. Using Built-in Functions:

  • Use the built-in function to convert the string to a number.
JavaScript
let str_num = "123";  // Step 1 let num = parseInt(str_num);  console.log(num); 

Output
123 

2. String Concatenation:

  • Check if the string represents a negative number and set a flag.
  • Iterate over each character of the string and convert it to its corresponding numerical value.
  • Calculate the numerical value using the digits.
JavaScript
let str_num = "-123"; let sign = 1; let num = 0;  // Step 1 if (str_num[0] === '-') {     sign = -1;     str_num = str_num.slice(1); }  // Step 2 for (let c of str_num) {     num = num * 10 + parseInt(c); }  // Step 3 num *= sign;  console.log(num); 

Output
-123 

Conclusion:

Converting a string to a number involves interpreting the characters in the string as numerical values. This typically requires iterating through each character, converting it to its numeric equivalent, and considering any sign indicators. By following this process, strings can be transformed into their corresponding numeric representations, facilitating numerical operations and calculations in programming.


Next Article
How to Convert Number to String

C

code_r
Improve
Article Tags :
  • Programming

Similar Reads

  • How to Convert Number to String
    Given a numerical value, convert it into a string representation. In this article, we will provide a detailed overview about different ways to convert Number to String in different languages. Table of Content Convert Number to String in CConvert Number to String in C++Convert Number to String in Jav
    7 min read
  • How to Convert String to Number in TypeScript?
    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 TypeSc
    4 min read
  • How to convert a String into Number in PHP ?
    Strings in PHP can be converted to numbers (float/ int/ double) very easily. In most use cases, it won't be required since PHP does implicit type conversion. This article covers all the different approaches for converting a string into a number in PHP, along with their basic illustrations. There are
    4 min read
  • How to convert String to Float in PHP ?
    Converting a string to a float in PHP is a common requirement when handling numeric data stored in string format. This conversion allows the numeric string to be used in calculations or comparisons, ensuring accurate manipulation of data within the program. There are many methods to convert a string
    3 min read
  • How to convert a rational number to a decimal?
    Answer: Here are the steps to convert fractions to decimals :Make the fraction an incorrect fraction if it's a mixed number.Subtract the denominator from the numerator.Round the decimal off if the division does not come out evenly.A number System can be defined as a system of writing to express numb
    4 min read
  • How to Convert Pandas Columns to String
    Converting columns to strings allows easier manipulation when performing string operations such as pattern matching, formatting or concatenation. Pandas provides multiple ways to achieve this conversion and choosing the best method can depend on factors like the size of your dataset and the specific
    3 min read
  • String to Number Conversion in Julia
    Julia is a flexible, dynamic, and high-level programming language that can be used to write any application. Also, many of its features can be used for numerical analysis and computational science. Julia is being widely used in machine learning, visualization, and data science. Julia allows type con
    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
  • Words to Numbers Converter Tool in Python
    In this tutorial, we will guide you through the process of building a Word-to Numbers converter using Python. To enhance the user experience, we will employ the Tkinter library to create a simple and intuitive Graphical User Interface (GUI). This tool allows users to effortlessly convert words into
    2 min read
  • Swift - Convert String to Int Swift
    Swift provides a number of ways to convert a string value into an integer value. Though, we can convert a numeric string only into an integer value. In this article, we will see the two most common methods used to convert a string to an integer value. A string is a collection of characters. Swift pr
    3 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