格式字符串/数字“NNNNN”

时间:2013-04-18 09:41:32

标签: c# string numbers format

我必须写一个数字的进展,有(每个)5位数。我的代码是:

int count = 1;
string labelCount = "";
foreach (var directory in folderList)
{
    if (count < 10)
    {
        labelCount = "0000" + count.ToString();
    }
    else if (count < 100)
    {
        labelCount = "000" + count.ToString();
    }
    else if (count < 1000)
    {
        labelCount = "00" + count.ToString();
    }
    else if (count < 10000)
    {
        labelCount = "0" + count.ToString();
    }

    count++;
}

但在我看来它看起来并不那么好。有没有办法格式化数字(左边加上0xN)或者这是唯一的方法?

5 个答案:

答案 0 :(得分:7)

只需将格式提供给ToString方法

即可
var str = count.ToString("00000");

答案 1 :(得分:5)

看看String.PadLeft

string formatted = count.ToString().PadLeft(6, '0');

答案 2 :(得分:0)

尝试如下,它会帮助你...

labelCount  = string.Format("{0:00000}", count);

请参阅此处查看所有格式:String.Format

答案 3 :(得分:0)

这样怎么样?

int count = 1;
string labelCount = "";

foreach (var directory in folderList)
{
   int i = 10000;
   while (count < i)
   {
       labelCount += 0;
       i /= 10;
   }

   labelCount += count.ToString();
   count++;
}

答案 4 :(得分:-2)

您可以通过执行以下操作来实现此目的:

string formatted = count.ToString();
for(int i = 0; i < count - 5; i++)
{
    formatted = "0" + formatted;
}
labelCount.Text = formatted;
编辑:讽刺,我的错!应该是:

//..
for(int i = 0; i < 5 - count.ToString().Length; i++)
//..