String to int conversion varies by programming language, but common methods include:

  • Java: Use Integer.parseInt() for primitive int or Integer.valueOf() for Integer objects. Both throw NumberFormatException if the string is not a valid number.

    • Example: int num = Integer.parseInt("123");

  • C++: Use std::stoi() (C++11+), which supports strings and C-style strings, or atoi() for C-style strings only. std::stoi() allows specifying base and handles errors better.

    • Example: int num = std::stoi("45");

  • C#: Use Convert.ToInt32() or int.TryParse() for safe conversion with error handling.

    • Example: int num = Convert.ToInt32("789");

  • Python: Use int() directly.

    • Example: num = int("100")

  • Go: Use strconv.Atoi() for string-to-int conversion.

    • Example: num, err := strconv.Atoi("567")

Always handle potential exceptions or errors when converting strings to integers, especially with user input.

String myString = "1234";
int foo = Integer.parseInt(myString);

If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which you can handle:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
   foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)
Answer from Rob Hruska on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › different-ways-for-integer-to-string-conversions-in-java
Java Convert int to String | How to Convert an Integer into a String - GeeksforGeeks
April 9, 2025 - But if the variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke its toString() method as shown above. Note: This method is not efficient as an instance of the Integer class is created ...
Discussions

Java - Convert integer to string - Stack Overflow
Given a number: int number = 1234; Which would be the "best" way to convert this to a string: String stringNumber = "1234"; I have tried searching (googling) for an answer but no many seemed " More on stackoverflow.com
🌐 stackoverflow.com
c - Integer array to string - Code Review Stack Exchange
This function creates takes an int * buffer and creates a neatly formatted string (useful for printing the contents of an array). Is the code easy to follow? Is it efficient? Am I allocating and f... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
May 22, 2022
java - How do I convert from int to String? - Stack Overflow
I'm working on a project where all conversions from int to String are done like this: int i = 5; String strI = "" + i; I'm not familiar with Java. Is this usual practice or is something wrong, a... More on stackoverflow.com
🌐 stackoverflow.com
How does computer converts integer to string?
It somewhat depends on the character set used. For ASCII, it's literally just a big lookup table that maps number to character. For unicode it's a bit more complex but on a basic level it's still similar. More on reddit.com
🌐 r/learnprogramming
16
82
March 29, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-string-to-int-in-java
String to int in Java - GeeksforGeeks
Note: valueOf() method uses parseInt() internally to convert to integer. ... // Java ProgramConvert String to int // using Integer.valueOf() Method public class StringToInt { public static void main(String[] args) { // Convert String to Integer using valueOf() String s = "217"; // Convert the string to an Integer object // using Integer.valueOf() int n = Integer.valueOf(s); System.out.println("" + n); } }
Published   July 23, 2025
🌐
LeetCode
leetcode.com › problems › string-to-integer-atoi
String to Integer (atoi) - LeetCode
String to Integer (atoi) - Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: 1. Whitespace: Ignore any leading whitespace (" "). 2. Signedness: Determine ...
Find elsewhere
Top answer
1 of 16
983

Normal ways would be Integer.toString(i) or String.valueOf(i).

The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).

Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();

at compile-time. It's slightly less efficient (sb.append() ends up calling Integer.getChars(), which is what Integer.toString() would've done anyway), but it works.

To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:

simon@lucifer:~$ cat TestClass.java
public class TestClass {
  public static void main(String[] args) {
    int i = 5;
    String strI = "" + i;
  }
}
simon@lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."<init>":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    iconst_5
   1:    istore_1

Initialise the StringBuilder:

   2:    new    #2; //class java/lang/StringBuilder
   5:    dup
   6:    invokespecial    #3; //Method java/lang/StringBuilder."<init>":()V

Append the empty string:

   9:    ldc    #4; //String
   11:    invokevirtual    #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;

Append the integer:

   14:    iload_1
   15:    invokevirtual    #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;

Extract the final string:

   18:    invokevirtual    #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
   21:    astore_2
   22:    return
}

There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.

2 of 16
258

It's acceptable, but I've never written anything like that. I'd prefer this:

String strI = Integer.toString(i);
🌐
Baeldung
baeldung.com › home › java › java array › converting a string array into an int array in java
Converting a String Array Into an int Array in Java | Baeldung
January 8, 2024 - In this quick tutorial, let’s explore how to convert an array of String into an array of int in Java.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › convert-string-to-int-in-cpp
Convert String to int in C++ - GeeksforGeeks
September 19, 2025 - Above program converts a string ... in a "Bad Input" message and terminate the program. The strtol function is used to converts a string to a long integer value, respectively....
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › programming-guide › types › how-to-convert-a-string-to-a-number
How to convert a string to a number - C# | Microsoft Learn
Download Microsoft Edge More info about Internet Explorer and Microsoft Edge ... Access to this page requires authorization. You can try signing in or changing directories. Access to this page requires authorization. You can try changing directories. ... You convert a string to a number by calling the Parse or TryParse method found on numeric types (int, long, double, and so on), or by using methods in the System.Convert class.
🌐
Autodesk
help.autodesk.com › cloudhelp › ENU › MayaCRE-Tech-Docs › Commands › intArrayToString.html
intArrayToString command
Go to: Synopsis. Return value. MEL examples. string intArrayToString( int $array[], string $separationString ) Return a string that combines all the integer elements of $array, each separated by the separation string.
Top answer
1 of 16
1183

In C++11 there are some nice new convert functions from std::string to a number type.

So instead of

atoi( str.c_str() )

you can use

std::stoi( str )

where str is your number as std::string.

There are version for all flavours of numbers: long stol(string), float stof(string), double stod(string),... see http://en.cppreference.com/w/cpp/string/basic_string/stol

2 of 16
119

The possible options are described below:

1. sscanf()

    #include <cstdio>
    #include <string>

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        if(sscanf(str.c_str(), "%d", &i) != 1)
            // error management

        // string -> float
        if(sscanf(str.c_str(), "%f", &f) != 1)
            // error management
    
        // string -> double 
        if(sscanf(str.c_str(), "%lf", &d) != 1)
            // error management

This is an error (also shown by cppcheck) because "scanf without field width limits can crash with huge input data on some versions of libc" (see here, and here).

2. std::sto()*

    #include <iostream>
    #include <string>

        int i;
        float f;
        double d;
        std::string str;

        try {
            // string -> integer
            int i = std::stoi(str);

            // string -> float
            float f = std::stof(str);

            // string -> double 
            double d = std::stod(str);
        } catch (...) {
            // error management
        }   

This solution is short and elegant, but it is available only on on C++11 compliant compilers.

3. sstreams

    #include <string>
    #include <sstream>

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        std::istringstream ( str ) >> i;

        // string -> float
        std::istringstream ( str ) >> f;

        // string -> double 
        std::istringstream ( str ) >> d;

        // error management ??

However, with this solution is hard to distinguish between bad input (see here).

4. Boost's lexical_cast

    #include <boost/lexical_cast.hpp>
    #include <string>

        std::string str;

        try {
            int i = boost::lexical_cast<int>( str.c_str());
            float f = boost::lexical_cast<int>( str.c_str());
            double d = boost::lexical_cast<int>( str.c_str());
            } catch( boost::bad_lexical_cast const& ) {
                // Error management
        }

However, this is just a wrapper of sstream, and the documentation suggests to use sstream for better error management (see here).

5. strto()*

This solution is very long, due to error management, and it is described here. Since no function returns a plain int, a conversion is needed in case of integer (see here for how this conversion can be achieved).

6. Qt

    #include <QString>
    #include <string>

        bool ok;
        std::string;

        int i = QString::fromStdString(str).toInt(&ok);
        if (!ok)
            // Error management
    
        float f = QString::fromStdString(str).toFloat(&ok);
        if (!ok)
            // Error management 

        double d = QString::fromStdString(str).toDouble(&ok);
        if (!ok)
    // Error management     
    

Conclusions

Summing up, the best solution is C++11 std::stoi() or, as a second option, the use of Qt libraries. All other solutions are discouraged or buggy.

🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-integer-to-string-in-python
Convert integer to string in Python - GeeksforGeeks
str() function is the simplest and most commonly used method to convert an integer to a string.
Published   July 12, 2025