Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 852
hypermiler Avatar asked Feb 16 '14 21:02

hypermiler


People also ask

How do you generate a random number of fixed length in Java?

To generate a 6-digit number:Random rnd = new Random(); int n = 100000 + rnd. nextInt(900000); Note that n will never be 7 digits (1000000) since nextInt(900000) can at most return 899999 .

How do you generate a random number in JavaScript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.

How do I generate a random 6 digit number in node JS?

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.


1 Answers

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.

like image 60
Cilan Avatar answered Sep 26 '22 20:09

Cilan