int值低于10转换为字符串两位数

Sun*_*Lim 110 c# string

string strI;   

for (int i = 1; i < 100; i++)
    strI = i.ToString();
Run Code Online (Sandbox Code Playgroud)

在这里,如果i = 1那么ToString收益"1"

但我想得到 "01""001"

它看起来很简单,但只有文章

datetime.ToString("yyyy-MM-dd")`
Run Code Online (Sandbox Code Playgroud)

MPr*_*ard 227

i.ToString("00")
Run Code Online (Sandbox Code Playgroud)

要么

i.ToString("000")
Run Code Online (Sandbox Code Playgroud)

取决于你想要什么

查看有关自定义数字格式字符串的MSDN文章以获取更多选项:http://msdn.microsoft.com/en-us/library/0c899ak8(VS.71).aspx


jp2*_*ode 11

接受的答案是好的和快速的:

i.ToString("00")
Run Code Online (Sandbox Code Playgroud)

要么

i.ToString("000")
Run Code Online (Sandbox Code Playgroud)

如果您需要更多复杂性,String.Format值得一试:

var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
    str1 = String.Format("{0:00}", i);
    str2 = String.Format("{0:000}", i);
}
Run Code Online (Sandbox Code Playgroud)

对于这种i = 10情况:

str1: "10"
str2: "010"

例如,我使用它来按名称清除表单上特定Label控件的文本:

private void EmptyLabelArray()
{
    var fmt = "Label_Row{0:00}_Col{0:00}";
    for (var rowIndex = 0; rowIndex < 100; rowIndex++)
    {
        for (var colIndex = 0; colIndex < 100; colIndex++)
        {
            var lblName = String.Format(fmt, rowIndex, colIndex);
            foreach (var ctrl in this.Controls)
            {
                var lbl = ctrl as Label;
                if ((lbl != null) && (lbl.Name == lblName))
                {
                    lbl.Text = null;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ite 5

这篇博文是一个很棒的小作弊表,在尝试将字符串格式化为各种格式时保持方便.

链接到木马删除

编辑

该链接已被删除,因为谷歌暂时警告该网站(或相关网站)可能已传播恶意软件.它现在不在列表中,不再报告有问题.Google"SteveX String Formatting"您可以找到搜索结果,您可以自行决定访问它.


niv*_*978 5

我不敢相信没有人建议这样做:

int i = 9;
i.ToString("D2"); // Will give you the string "09"
Run Code Online (Sandbox Code Playgroud)

要么

i.ToString("D8"); // Will give you the string "00000009"
Run Code Online (Sandbox Code Playgroud)

如果要十六进制:

byte b = 255;
b.ToString("X2"); // Will give you the string "FF"
Run Code Online (Sandbox Code Playgroud)

如果您使用区域设置货币符号,甚至可以只使用“ C”显示为货币。参见此处:https : //docs.microsoft.com/zh-cn/dotnet/api/system.int32.tostring?view=netframework-4.7.2#System_Int32_ToString_System_String_