C#将int转换为带填充零的字符串?

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");- 短格式格式说明符

  • i.ToString().PadLeft(4,'0')不适用于负数,例如(-5).PadLeft(4,'0')将为"00-5" (24认同)
  • 使用String格式快捷键也可以使用例如$"{i:D4}"; (13认同)
  • 如何显示固定长度的字符串.?? (5认同)
  • @Rahul阅读本文:https://msdn.microsoft.com/en-us/library/dwhawy9k(v = vs.110).aspx#FFormatString (3认同)
  • 这种方式对我有用String.Format("{0:D4}",数字); (2认同)

Rya*_*yan 271

i.ToString("D4");
Run Code Online (Sandbox Code Playgroud)

有关格式说明符,请参阅MSDN.

  • 这种方式对我有用String.Format("{0:D4}",数字); (4认同)

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)

  • 第二种方法是使用相同的格式字符串:`string.Format("{0:0000}",x)` (26认同)

Dr *_*ard 51

C#6.0样式字符串插值

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";
Run Code Online (Sandbox Code Playgroud)


cah*_*yaz 5

简单地

int i=123;
string paddedI = i.ToString("D4");
Run Code Online (Sandbox Code Playgroud)


mae*_*eak 5

十分简单

int i = 1;
i.ToString("0###")
Run Code Online (Sandbox Code Playgroud)

  • 不知道你为什么不赞成它的工作原理并回答操作问题 (3认同)