Generate random 6 digit number
93,467
Solution 1
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");
Solution 2
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"
Solution 3
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);
}
Solution 4
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");
Solution 5
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');
Author by
Arvin Ashrafi
Updated on July 09, 2022Comments
-
Arvin Ashrafi almost 2 years
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 me to use this code:
Random generator = new Random(); int r = generator.Next(100000, 1000000);
But that limits my 6 digits to all be above 100 000 in value. I want to be able to generate a int with 000 001, 000 002 etc. I later want to convert this integer to a string.