I am generating Random Number with
int randomID = arc4random() % 3000;
But I want to generate random number with atleast 4 digits. like 1000, 2400, 1122
I want to know the code for Objective C.
Please try
generate numbers :1000~9999
int randomID = arc4random() % 9000 + 1000;
generate numbers :1000~2999
int randomID = arc4random() % 2000 + 1000;
At least four digits, right?
So you need something with flexibility:
-(NSString *)getRandomPINString:(NSInteger)length
{
NSMutableString *returnString = [NSMutableString stringWithCapacity:length];
NSString *numbers = @"0123456789";
// First number cannot be 0
[returnString appendFormat:@"%C", [numbers characterAtIndex:(arc4random() % ([numbers length]-1))+1]];
for (int i = 1; i < length; i++)
{
[returnString appendFormat:@"%C", [numbers characterAtIndex:arc4random() % [numbers length]]];
}
return returnString;
}
and use it like so:
NSString *newPINString = [self getRandomPINString:4];
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