Generate random 6 digit number

You want to have a string:

Random r = new Random();
var x = r.Next(0, 1000000);
string s = x.ToString("000000");

For example,

x = "2124"
s = "002124"

private static string _numbers = "0123456789";
Random random = new Random();


private void DoWork()
{
   StringBuilder builder = new StringBuilder(6);
   string numberAsString = "";
   int numberAsNumber = 0;

   for (var i = 0; i < 6; i++)
   {
      builder.Append(_numbers[random.Next(0, _numbers.Length)]);
   }

   numberAsString = builder.ToString();
   numberAsNumber = int.Parse(numberAsString);

}

As stated in a comment, a "six digit number" is a string. Here's how you generate a number from 0-999999, then format it like "000482":

Random r = new Random();
int randNum = r.Next(1000000);
string sixDigitNumber = randNum.ToString("D6");

If you want a string to lead with zeroes, try this. You cannot get an int like 001.

    Random generator = new Random();
    String r = generator.Next(0, 1000000).ToString("D6");

Tags:

C#