Convert int to string?
Advertisement
Convert int to string?
Popular Answer
string s = i.ToString();
string s = Convert.ToString(i);
string s = string.Format("{0}", i);
string s = $"{i}";
string s = "" + i;
string s = string.Empty + i;
string s = new StringBuilder().Append(i).ToString();
2017/01/23
Read more… Read less…
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
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
string str = intVar.ToString();
In some conditions, yo do not have to use ToString()
string str = "hi " + intVar;
2013/05/25
Licensed under CC-BY-SA with attribution
Not affiliated with Stack Overflow
Email: [email protected]