I want to generate a random six-digit number. I tried to use the Random
class, but new Random().nextInt(999999)
generates some numbers with less than six digits.
How to generate 6 digit random number
26.7k views Asked by Osama Gamal At
11
There are 11 answers
0
On
i had the same problem.although there are 3-4 ways to tackle it but i find the below one simple and sorted. simply check for the number of length match. find below code
Integer otp = new Random().nextInt(999999);
int noOfOtpDigit=6;
while(Integer.toString(otp).length()!=noOfOtpDigit) {
otp = new Random().nextInt(999999);
}
String otpString = String.valueOf(otp);
0
On
why not a generic function so you can use it anywhere? If the input is 1 then it will generate 1 digit number, if 2 then 2 digit number and so on.
import 'dart:math';
int generateRandomNumber(int input) {
if (input < 1) {
throw ArgumentError("Input should be at least 1");
}
int min = pow(10, input - 1).toInt();
int max = pow(10, input).toInt() - 1;
Random random = Random();
int randomNumber = min + random.nextInt(max - min + 1);
return randomNumber;
}
void main() {
int userInput = 4; // Change this to the desired input value
int randomOutput = generateRandomNumber(userInput);
print("Generated Random Number: $randomOutput");
}
0
On
The following class will generate an integer with 'n' digits, or a string with 'n' digits.
The numeric method will be much faster, but is limited in the number of digits.
import 'dart:math';
class RandomDigits {
static const MaxNumericDigits = 17;
static final _random = Random();
static int getInteger(int digitCount) {
if (digitCount > MaxNumericDigits || digitCount < 1) throw new RangeError.range(0, 1, MaxNumericDigits, "Digit Count");
var digit = _random.nextInt(9) + 1; // first digit must not be a zero
int n = digit;
for (var i = 0; i < digitCount - 1; i++) {
digit = _random.nextInt(10);
n *= 10;
n += digit;
}
return n;
}
static String getString(int digitCount) {
String s = "";
for (var i = 0; i < digitCount; i++) {
s += _random.nextInt(10).toString();
}
return s;
}
}
void main() {
print(RandomDigits.getInteger(6));
print(RandomDigits.getString(36));
}
Output:
995723
198815207332880163668637448423456900
0
On
Here is a Dart extension method that will generate a non-negative random integer with a specified number of digits:
extension RandomOfDigits on Random {
/// Generates a non-negative random integer with a specified number of digits.
///
/// Supports [digitCount] values between 1 and 9 inclusive.
int nextIntOfDigits(int digitCount) {
assert(1 <= digitCount && digitCount <= 9);
int min = digitCount == 1 ? 0 : pow(10, digitCount - 1);
int max = pow(10, digitCount);
return min + nextInt(max - min);
}
}
In your case use it like this:
final random = Random();
print(random.nextIntOfDigits(6));