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

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

    I created the below function to generate random number of fix length:

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

    This will basically add 0's at the beginning to make the length of the number as required.

提交回复
热议问题