Advertisement
Advertisement


Convert int to string?


Question

How can I convert an int datatype into a string datatype in C#?

2014/06/09
1
509
6/9/2014 4:33:03 AM

Accepted Answer

string myString = myInt.ToString();
2020/03/14
751
3/14/2020 1:20:30 AM


Just in case you want the binary representation and you're still drunk from last nights party:

private static string ByteToString(int value)
{
    StringBuilder builder = new StringBuilder(sizeof(byte) * 8);
    BitArray[] bitArrays = BitConverter.GetBytes(value).Reverse().Select(b => new BitArray(new []{b})).ToArray();
    foreach (bool bit in bitArrays.SelectMany(bitArray => bitArray.Cast<bool>().Reverse()))
    {
        builder.Append(bit ? '1' : '0');
    }
    return builder.ToString();
}

Note: Something about not handling endianness very nicely...

Edit: If you don't mind sacrificing a bit of memory for speed, you can use below to generate an array with pre-calculated string values:

static void OutputIntegerStringRepresentations()
{
    Console.WriteLine("private static string[] integerAsDecimal = new [] {");
    for (int i = int.MinValue; i < int.MaxValue; i++)
    {
        Console.WriteLine("\t\"{0}\",", i);
    }
    Console.WriteLine("\t\"{0}\"", int.MaxValue);
    Console.WriteLine("}");
}
2017/07/12

int num = 10;
string str = Convert.ToString(num);
2010/06/21

The ToString method of any object is supposed to return a string representation of that object.

int var1 = 2;

string var2 = var1.ToString();
2010/06/21

Further on to @Xavier's response, here's a page that does speed comparisons between several different ways to do the conversion from 100 iterations up to 21,474,836 iterations.

It seems pretty much a tie between:

int someInt = 0;
someInt.ToString(); //this was fastest half the time
//and
Convert.ToString(someInt); //this was the fastest the other half the time
2014/09/06

string str = intVar.ToString();

In some conditions, yo do not have to use ToString()

string str = "hi " + intVar;
2013/05/25

Source: https://stackoverflow.com/questions/3081916
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]