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

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

    const generate = n => String(Math.ceil(Math.random() * 10**n)).padStart(n, '0')
    // n being the length of the random number.
    

    Use a parseInt() or Number() on the result if you want an integer. If you don't want the first integer to be a 0 then you could use padEnd() instead of padStart().

提交回复
热议问题