I\'ve been searching for a couple of hours and I just can\'t seem to find a answer to this question. I want to generate a random number with 6 digits. Some of you might tell
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");
I agree with the comment above that 000 001 can't be an integer, but can be a string with:
Random generator = new Random();
int r = generator.Next(1, 1000000);
string s = r.ToString().PadLeft(6, '0');
string s = generator.Next(0, 1000000).ToString("D6");
or
string s = generator.Next(0, 1000000).ToString("000000");
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);
}
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"
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");