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

前端 未结 22 2360
攒了一身酷
攒了一身酷 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:53

    More generally, generating a random integer with fixed length can be done using Math.pow:

    var randomFixedInteger = function (length) {
        return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
    }
    

    To answer the question: randomFixedInteger(6);

提交回复
热议问题