简体   繁体   中英

Convert int to string?

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

string myString = myInt.ToString();
string a = i.ToString();
string b = Convert.ToString(i);
string c = string.Format("{0}", i);
string d = $"{i}";
string e = "" + i;
string f = string.Empty + i;
string g = new StringBuilder().Append(i).ToString();

Just in case you want the binary representation and you're still drunk from last night's 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...


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("}");
}
int num = 10;
string str = Convert.ToString(num);

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

int var1 = 2;

string var2 = var1.ToString();

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();

在某些情况下,您不必使用ToString()

string str = "hi " + intVar;

或者:

string s = Convert.ToString(num);
using System.ComponentModel;

TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
string s = (string)converter.ConvertTo(i, typeof(string));

None of the answers mentioned that the ToString() method can be applied to integer expressions

Debug.Assert((1000*1000).ToString()=="1000000");

even to integer literals

Debug.Assert(256.ToString("X")=="100");

Although integer literals like this are often considered to be bad coding style ( magic numbers ) there may be cases where this feature is useful...

string s = "" + 2;

and you can do nice things like:

string s = 2 + 2 + "you" 

The result will be:

"4 you"

if you're getting from a dataset

string newbranchcode = (Convert.ToInt32(ds.Tables[0].Rows[0]["MAX(BRANCH_CODE)"]) ).ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM