javascriptrandomnumbers

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


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 than 6 digits?

Math.floor((Math.random()*1000000)+1);

I found this question and answer on StackOverflow here. But, it's unclear.

EDIT: I ran the above code a bunch of times, and Yes, it frequently creates numbers less than 6 digits. Is there a quick/fast way to make sure it's always exactly 6 digits?


Solution

  • console.log(Math.floor(100000 + Math.random() * 900000));

    Will always create a number of 6 digits and it ensures the first digit will never be 0. The code in your question will create a number of less than 6 digits.