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

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

    You can use the below code to generate a random number that will always be 6 digits:

    Math.random().toString().substr(2, 6)
    

    Hope this works for everyone :)

    Briefly how this works is Math.random() generates a random number between 0 and 1 which we convert to a string and using .toString() and take a 6 digit sample from said string using .substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters.

    This can be used for any length number.

    If you want to do more reading on this here are some links to the docs to save you some googling:

    Math.random(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

    .toString(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

    .substr(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

提交回复
热议问题