C# 将字符串格式化为 3 位数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12570807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format string to a 3 digit number
提问by Alex
Instead of doing this, I want to make use of string.format()to accomplish the same result:
而不是这样做,我想利用string.format()来完成相同的结果:
if (myString.Length < 3)
{
myString = "00" + 3;
}
采纳答案by Reed Copsey
If you're just formatting a number, you can just provide the proper custom numeric formatto make it a 3 digit string directly:
如果您只是格式化数字,则可以提供正确的自定义数字格式以直接将其设为 3 位字符串:
myString = 3.ToString("000");
Or, alternatively, use the standard D format string:
或者,使用标准 D 格式字符串:
myString = 3.ToString("D3");
回答by user287107
"How to: Pad a Number with Leading Zeros" http://msdn.microsoft.com/en-us/library/dd260048.aspx
“如何:用前导零填充数字” http://msdn.microsoft.com/en-us/library/dd260048.aspx
回答by Sconibulus
Does it have to be String.Format?
必须是String.Format吗?
This looks like a job for String.Padleft
这看起来像是一份工作 String.Padleft
myString=myString.PadLeft(3, '0');
Or, if you are converting direct from an int:
或者,如果您直接从 int 转换:
myInt.toString("D3");
回答by Haitham Salem
string.Format("{0:000}", myString);
回答by sstassin
You can also do : string.Format("{0:D3}, 3);
你也可以这样做: string.Format("{0:D3}, 3);
回答by Sxc
(Can't comment yet with enough reputation , let me add a sidenote)
(还不能评论有足够的声誉,让我添加一个旁注)
Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000on it .
以防万一您的输出需要固定长度为 3 位,即数字运行高达 1000 或更多(保留固定长度),不要忘记在其上添加 mod 1000。
yourNumber=1001;
yourString= yourNumber.ToString("D3"); // "1001"
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected
Trail sample on Fiddler https://dotnetfiddle.net/qLrePt
Fiddler 上的跟踪示例https://dotnetfiddle.net/qLrePt
回答by Ali
This is how it's done using string interpolation C# 7
这是如何使用字符串插值 C# 7 完成的
$"{myString:000}"

