- Instant help with your JavaScript coding problems

Generate a random number with fixed length using JavaScript

Question:
How to generate a random number with fixed length using JavaScript?
Answer:
function getRandumNumber(length) {
    const min = Math.pow(10, (length-1));
    const max = Math.pow(10, (length));
    return Math.floor(Math.random() * (max - min) + min);
}

const num = getRandumNumber(3);
Description:

To generate a fixed-length random number is similar to generating a random integer in a range. In this case, the range should be determined first based on the given length. After calculating the min and max value of the range you can Math.random with the extra operations and rounding.

 

Share "How to generate a random number with fixed length using JavaScript?"