-3

i have a variable say

             a=000000;

My requirement is when i loop this variable from 1 to 100 it will increment one by one ,like

    for loop 1 the value in 'a' will be 000001
    for loop 2 the value in 'a' will be 000002 like that

up to 100 it will be 000100.Any idea?

ranjenanil
  • 308
  • 2
  • 7
  • 19

3 Answers3

2

You can use PadLeft to format like that.

int intVariable = 0;
intVariable++; 
string output = intVariable.ToString().PadLeft(6, '0');

A new string that is equivalent to this instance, but right-aligned and padded on the left with as many paddingChar characters as needed to create a length of totalWidth. However, if totalWidth is less than the length of this instance, the method returns a reference to the existing instance. If totalWidth is equal to the length of this instance, the method returns a new string that is identical to this instance, MSDN.

To generate in loop, you can use loop variable.

  for(int i=0; i < 100; i++)    
       output = i.ToString().PadLeft(6, '0');
Adil
  • 146,340
  • 25
  • 209
  • 204
2

Use int's overload of ToString that takes a parameter and pass it the string D6:

foreach (int x in Enumerable.Range(1, 100)) 
    Console.WriteLine(x.ToString("D6"))
It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
1

Try something like, this will keep always 6 digits

   for (int i = 1; i < 20; i++)
   {
      Console.WriteLine(String.Format("{0:000000}", i));
   }
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99