在c#中,我有一个整数值,需要转换为字符串,但它需要在前面加零:
例如:
int i = 1;
当我把它转换成字符串时,它需要变成0001
我需要知道c#中的语法。
在c#中,我有一个整数值,需要转换为字符串,但它需要在前面加零:
例如:
int i = 1;
当我把它转换成字符串时,它需要变成0001
我需要知道c#中的语法。
当前回答
int p = 3; // fixed length padding
int n = 55; // number to test
string t = n.ToString("D" + p); // magic
Console.WriteLine("Hello, world! >> {0}", t);
// outputs:
// Hello, world! >> 055
其他回答
容易peasy
int i = 1;
i.ToString("0###")
这里有一个很好的例子:
int number = 1;
//D4 = pad with 0000
string outputValue = String.Format("{0:D4}", number);
Console.WriteLine(outputValue);//Prints 0001
//OR
outputValue = number.ToString().PadLeft(4, '0');
Console.WriteLine(outputValue);//Prints 0001 as well
string hello = "Hello C# Corner.";
string helloHash = hello.PadLeft(5, '#');
Console.WriteLine(helloHash);
输出:
#####Hello C# Corner.
i.ToString("D4");
关于格式说明符,请参阅MSDN。
int p = 3; // fixed length padding
int n = 55; // number to test
string t = n.ToString("D" + p); // magic
Console.WriteLine("Hello, world! >> {0}", t);
// outputs:
// Hello, world! >> 055