I\'m trying to generate a random number that must have a fixed length of exactly 6 digits.
I don\'t know if JavaScript has given below would ever create a number less th
For the length of 6, recursiveness doesn't matter a lot.
function random(len) {
let result = Math.floor(Math.random() * Math.pow(10, len));
return (result.toString().length < len) ? random(len) : result;
}
console.log(random(6));
Here is my function I use. n - string length you want to generate
function generateRandomNumber(n) {
return Math.floor(Math.random() * (9 * Math.pow(10, n - 1))) + Math.pow(10, n - 1);
}
I use randojs to make the randomness simpler and more readable. you can pick a random int between 100000 and 999999 like this with randojs:
console.log(rando(100000, 999999));
<script src="https://randojs.com/1.0.0.js"></script>
var number = Math.floor(Math.random() * 9000000000) + 1000000000;
console.log(number);
This can be simplest way and reliable one.
parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random
Update: This method has few flaws: - Sometimes the number of digits might be lesser if its left padded with zeroes.
I would go with this solution:
Math.floor(Math.random() * 899999 + 100000)