Generate random number using specific digits in javascript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/19022480/generate-random-number-using-specific-digits-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils