C# 将 int 1、10、100 格式化为字符串“001”、“010”、“100”的掩码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10606082/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:28:36  来源:igfitidea点击:

Mask to format int 1, 10, 100, to string "001", "010", "100"

c#

提问by Jo?o Paulo Navarro

How do I apply a mask to a string aiming to format the output text in the following fashion (at most 2 leading zeros):

如何将掩码应用于旨在以以下方式格式化输出文本的字符串(最多 2 个前导零):

int a = 1, b = 10, c = 100;
string aF = LeadingZeroFormat(a), bF = LeadingZeroFormat(b), cF = LeadingZeroFormat(c);
Console.Writeline("{0}, {1}, {2}", aF, bF, cF); // "001, 010, 100" 

What is the most elegant solution?

什么是最优雅的解决方案?

Thanks in advance.

提前致谢。

采纳答案by Reed Copsey

You can use Int32.ToString("000") to format an integer in this manner. For details, see Custom Numeric Format Stringsand Int32.ToString:

您可以使用 Int32.ToString("000") 以这种方式格式化整数。有关详细信息,请参阅自定义数字格式字符串Int32.ToString

string one = a.ToString("000"); // 001
string two = b.ToString("000"); // 010

回答by Jon Skeet

As well as Reed's suggestion, you can do it directly in your compound format string:

除了 Reed 的建议,您还可以直接在复合格式字符串中执行此操作:

int a = 1, b = 10, c = 100;
Console.WriteLine("{0:000}, {1:000}, {2:000}", a, b, c); // "001, 010, 100"

回答by Habib

To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

要将整数显示为十进制值,请调用其 ToString(String) 方法,并将字符串“Dn”作为格式参数的值传递,其中 n 表示字符串的最小长度。

int i = 10;
Console.WriteLine(i.ToString("D3"));

Also check How to: Pad a Number with Leading Zeros

另请检查如何:用前导零填充数字