I want to generate an unique 4 digit random number. This is the below code what I have tried:
Code for generating random number
//Generate RandomNo
public int GenerateRandomNo()
{
int _min = 0000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
The problem is I have received a random no with value 241
which is not a 4 digit number. Is there any problems with the code?
//Generate RandomNo
public int GenerateRandomNo()
{
int _min = 1000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
you need a 4 digit code, start with 1000
Use this code instead:
private Random _random = new Random();
public string GenerateRandomNo()
{
return _random.Next(0, 9999).ToString("D4");
}
241 is a four digit number, if you use leading zeros: 0241.
Display the returned number with a format string like this:
String.Format("{0:0000}", n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With