David.Chu.ca
David.Chu.ca

Reputation: 38664

Quick way to build string with leading 0s for integer number?

I have built a string for an integer with prefix 0s if need like this way:

 // myInt as input, for example: 101;
 List<string> sList = new List<string>();
 string format = "00#"; // how to build format dynamicall?
 for(int i= 1; i <= myInt; i++)
 {
     sList.Add(i.ToString(format));
 }

The expected result should be:

 001
 002
 ...
 010
 ...
 101

If my integer number is 10 or 1000, how can I build the format dynamically?

Upvotes: 1

Views: 394

Answers (4)

opello
opello

Reputation: 3274

You can use log base 10 with ceil to get the digit length of a number.

int i = 123;
int len = Convert.ToInt32(Math.Ceiling(Math.Log10(i)));

Since C# can implicitly convert the int to a double, it should be reliable. Then you can avoid the string conversion.

I've not benchmarked it against ToString() on the int, but it seems like it might be better.

Upvotes: 2

Scott Ivey
Scott Ivey

Reputation: 41568

How about just using the standard numeric format strings?

List<string> sList = new List<string>();
string format = string.Format("D{0}", myInt.ToString().Length);
for(int i= 1; i <= myInt; i++)
{
    sList.Add(i.ToString(format)); 
}

Upvotes: 3

Patrick McDonald
Patrick McDonald

Reputation: 65441

You don't need to use "00#", "000" will do the same job.

// myInt as input, for example: 101;
List<string> sList = new List<string>();
string format = new string('0', myInt.ToString().Length);
for(int i= 1; i <= myInt; i++)
{
    sList.Add(i.ToString(format));
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502186

How about "#".PadLeft(desiredWidth, '0')

You could get desiredWidth from myInt.ToString().Length - a bit grotty, but it'll work :)

In other words:

List<string> sList = new List<string>();
string format = "#".PadLeft(myInt.ToString().Length, '0');
for(int i= 1; i <= myInt; i++)
{
    sList.Add(i.ToString(format));
}

Alternatively you could skip the format string entirely:

List<string> sList = new List<string>();
int desiredWidth = myInt.ToString().Length;
for(int i= 1; i <= myInt; i++)
{
    sList.Add(i.ToString().PadLeft(desiredWidth, '0'));
}

Upvotes: 11

Related Questions