Pin*_*inu 425 c# formatting number-formatting
在C#中,我有一个整数值,需要对字符串进行控制,但需要在之前添加零:
例如:
int i = 1;
Run Code Online (Sandbox Code Playgroud)
当我将其转换为字符串时,它需要变为0001
我需要知道C#中的语法.
Jay*_*Jay 668
i.ToString().PadLeft(4, '0')
- 好吧,但不适用于负数
i.ToString("0000");
- 显式格式
i.ToString("D4");
- 短格式格式说明符
Rya*_*yan 271
i.ToString("D4");
Run Code Online (Sandbox Code Playgroud)
有关格式说明符,请参阅MSDN.
Den*_*els 115
这是一个很好的例子:
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
Run Code Online (Sandbox Code Playgroud)
Yod*_*ber 66
您可以使用:
int x = 1;
x.ToString("0000");
Run Code Online (Sandbox Code Playgroud)
Dr *_*ard 51
C#6.0样式字符串插值
int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";
Run Code Online (Sandbox Code Playgroud)
十分简单
int i = 1;
i.ToString("0###")
Run Code Online (Sandbox Code Playgroud)