Man*_*ton 225 c# string string-formatting
我有一个我需要转换为字符串的数字.首先我使用了这个:
Key = i.ToString();
Run Code Online (Sandbox Code Playgroud)
但我意识到它是按照一个奇怪的顺序排序,所以我需要用零填充它.我怎么能这样做?
Mar*_*rio 323
相当简单:
Key = i.ToString("D2");
Run Code Online (Sandbox Code Playgroud)
D代表"十进制数",2表示要打印的位数.
Pau*_*aul 188
有关String.Format的一些示例用法,请参阅C#中的字符串格式
实际上是格式化int的更好例子
String.Format("{0:00000}", 15); // "00015"
Run Code Online (Sandbox Code Playgroud)
$"{15:00000}"; // "00015"
Run Code Online (Sandbox Code Playgroud)
Øyv*_*hen 66
如果你想保持固定宽度,例如10位数,就这样做吧
Key = i.ToString("0000000000");
Run Code Online (Sandbox Code Playgroud)
替换为任意数量的数字.
i = 123然后会导致Key = "0000000123".
Dav*_*idG 58
由于没有人提到这一点,如果您使用的是C#6或更高版本(即Visual Studio 2015),那么您可以使用字符串插值来简化代码.所以不要使用string.Format(...),你可以这样做:
Key = $"{i:D2}";
Run Code Online (Sandbox Code Playgroud)
fir*_*986 30
使用:
i.ToString("D10")
Run Code Online (Sandbox Code Playgroud)
请参见Int32.ToString(MSDN)和标准数字格式字符串(MSDN).
或者使用String.PadLeft.例如,
int i = 321;
Key = i.ToString().PadLeft(10, '0');
Run Code Online (Sandbox Code Playgroud)
会导致0000000321.虽然String.PadLeft不适用于负数.
请参见String.PadLeft(MSDN).
Ala*_*met 17
对于内插字符串:
$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"
Run Code Online (Sandbox Code Playgroud)
Cha*_*age 14
通常String.Format("format",object)优于object.ToString("format").因此,
String.Format("{0:00000}", 15);
Run Code Online (Sandbox Code Playgroud)
比较好,
Key = i.ToString("000000");
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 13
尝试:
Key = i.ToString("000000");
Run Code Online (Sandbox Code Playgroud)
但就个人而言,我会看到你是否不能直接对整数进行排序,而不是字符串表示.
int num=1;
string number=num.ToString().PadLeft(4, '0')
Run Code Online (Sandbox Code Playgroud)
输出=“00001”
编辑:更改为匹配 PadLeft 数量