Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random 6 digit number

Tags:

c#

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.

like image 896
Arvin Ashrafi Avatar asked Mar 05 '14 20:03

Arvin Ashrafi


People also ask

How do I generate a random 6 digit number in node?

random() generates a random number between 0 and 1 which we convert to a string and using . toString() and take a 6 digit sample from said string using . substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters. This can be used for any length number.

How many random 6 digit numbers are there?

n = 900000 ∴ There are 900,000 6-digit numbers in all.


2 Answers

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"); 
like image 163
user3381672 Avatar answered Sep 21 '22 06:09

user3381672


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" 
like image 25
Matten Avatar answered Sep 22 '22 06:09

Matten