Reputation: 2096
In my program I want to generate 5 digit random number such the that contain only digits ( 1 to 7).
var randnum = Math.floor(Math.random() * (11111 - 77777 + 1)) + 11111;
Using above code I got number between 11111
and 77777
. But how to generate the number that does not contain 0,8,9
? Is there any default method to generate this kind of numbers?
Upvotes: 2
Views: 1442
Reputation: 27853
You can generate each digit at a time, concatenate them then parseInt to get your result:
var str = '';
for (var i=0; i<5; i++) {
str += Math.floor(Math.random()*7) + 1;
}
var randnum = parseInt(str);
Explanation
Math.random()
returns [0,1)
Math.random() * 7
returns [0,7)
Math.floor(...)
returns 0,1,2,3,4,5,6
...+1
returns 1,2,3,4,5,6,7
Upvotes: 2
Reputation: 215059
For example,
digits = [1,2,3,4,5,6,7]
len = 5
num = 0
while(len--)
num = num * 10 + digits[Math.floor(Math.random() * digits.length)]
console.log(num)
This way you can easily select which digits to use.
Upvotes: 1