在c#中,我有一个整数值,需要转换为字符串,但它需要在前面加零:
例如:
int i = 1;
当我把它转换成字符串时,它需要变成0001
我需要知道c#中的语法。
在c#中,我有一个整数值,需要转换为字符串,但它需要在前面加零:
例如:
int i = 1;
当我把它转换成字符串时,它需要变成0001
我需要知道c#中的语法。
当前回答
你可以使用:
int x = 1;
x.ToString("0000");
其他回答
这里有一个很好的例子:
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
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
i.ToString("D4");
关于格式说明符,请参阅MSDN。
简单的
int i=123;
string paddedI = i.ToString("D4");
i.ToString("0000");