Why is this function not working correctly?


I am trying to create a function that takes a parameter (n) and generates a random number of n digits.

I found a similar function on stack overflow that looks like this:

Math.floor(100000 + Math.random() * 900000). This creates a random 6 digit number every time.

I have attempted to write my own function like this:

const randomNDigitsNumber = (n) => Math.floor(Math.pow(1, n) + Math.random() * Math.pow(9, n));

My function works the majority of the time but it is occasionally one digit short?

Any ideas what I’m doing wrong?

What is the smallest number and the largest random number that would ever need to be generated? I assume n is the largest, but do you want n to at least be 1 or greater?

I have actually worked in out. Correct function should look like this:

const randomNDigitsNumber = (n) => Math.floor(Math.pow(10, n - 1) + Math.random() * 9 * Math.pow(10, n - 1));

Thanks for offering to help though!