Reputation: 1257
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.
Upvotes: 5
Views: 9207
Reputation: 928
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];
Upvotes: 8
Reputation: 1678
Please try
generate numbers :1000~9999
int randomID = arc4random() % 9000 + 1000;
generate numbers :1000~2999
int randomID = arc4random() % 2000 + 1000;
Upvotes: 24