3

我必须写一个数字的级数,有(每个)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)或者这是唯一的方法?

4

5 回答 5

7

只需为方法提供格式ToString

var str = count.ToString("00000");
于 2013-04-18T09:42:57.300 回答
5

看看String.PadLeft

string formatted = count.ToString().PadLeft(6, '0');
于 2013-04-18T09:42:49.113 回答
0

试试下面的方法,它会帮助你...

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

有关所有格式,请参见此处:String.Format

于 2013-04-18T09:47:24.570 回答
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++;
}
于 2013-04-18T09:52:51.933 回答
-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++)
//..
于 2013-04-18T09:44:48.313 回答