Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string/number "NNNNN"

I have to write a progression of number, having (each) 5 digit. My code is:

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++;
}

but it doesnt looks so good in my opinion. Is there a way to format a number (adding 0xN to the left) or that's the only way?

like image 817
markzzz Avatar asked Apr 26 '26 10:04

markzzz


2 Answers

Just give format to ToString method

var str = count.ToString("00000");
like image 90
I4V Avatar answered Apr 28 '26 00:04

I4V


Take a look at String.PadLeft:

string formatted = count.ToString().PadLeft(6, '0');
like image 36
User 12345678 Avatar answered Apr 28 '26 00:04

User 12345678



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!