How to Generate a random number of fixed length using JavaScript?

前端 未结 22 2351
攒了一身酷
攒了一身酷 2021-01-30 10:23

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

相关标签:
22条回答
  • 2021-01-30 10:33

    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));

    0 讨论(0)
  • 2021-01-30 10:34

    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);
    }

    0 讨论(0)
  • 2021-01-30 10:34

    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>

    0 讨论(0)
  • 2021-01-30 10:35

      var number = Math.floor(Math.random() * 9000000000) + 1000000000;
        console.log(number);

    This can be simplest way and reliable one.

    0 讨论(0)
  • 2021-01-30 10:36

    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.

    0 讨论(0)
  • 2021-01-30 10:39

    I would go with this solution:

    Math.floor(Math.random() * 899999 + 100000)
    
    0 讨论(0)
提交回复
热议问题