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

前端 未结 22 2349
攒了一身酷
攒了一身酷 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:40
    npm install --save randomatic
    
    var randomize = require('randomatic');
    randomize(pattern, length, options);
    

    Example:

    To generate a 10-character randomized string using all available characters:

    randomize('*', 10);
    //=> 'x2_^-5_T[$'
    
    randomize('Aa0!', 10);
    //=> 'LV3u~BSGhw'
    

    a: Lowercase alpha characters (abcdefghijklmnopqrstuvwxyz'

    A: Uppercase alpha characters (ABCDEFGHIJKLMNOPQRSTUVWXYZ')

    0: Numeric characters (0123456789')

    !: Special characters (~!@#$%^&()_+-={}[];\',.)

    *: All characters (all of the above combined)

    ?: Custom characters (pass a string of custom characters to the options)

    NPM repo

    0 讨论(0)
  • 2021-01-30 10:43

    "To Generate Random Number Using JS"

    console.log(
    Math.floor(Math.random() * 1000000)
    );
    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript Math.random()</h2>
    
    <p id="demo"></p>
    
    </body>
    </html>

    0 讨论(0)
  • 2021-01-30 10:43

    In case you also want the first digit to be able to be 0 this is my solution:

    const getRange = (size, start = 0) => Array(size).fill(0).map((_, i) => i + start);
    
    const getRandomDigit = () => Math.floor(Math.random() * 10);
    
    const generateVerificationCode = () => getRange(6).map(getRandomDigit).join('');
    
    console.log(generateVerificationCode())

    0 讨论(0)
  • 2021-01-30 10:45

    generate a random number that must have a fixed length of exactly 6 digits:

    ("000000"+Math.floor((Math.random()*1000000)+1)).slice(-6)
    
    0 讨论(0)
  • 2021-01-30 10:45
    const generate = n => String(Math.ceil(Math.random() * 10**n)).padStart(n, '0')
    // n being the length of the random number.
    

    Use a parseInt() or Number() on the result if you want an integer. If you don't want the first integer to be a 0 then you could use padEnd() instead of padStart().

    0 讨论(0)
  • 2021-01-30 10:48

    I created the below function to generate random number of fix length:

    function getRandomNum(length) {
        var randomNum = 
            (Math.pow(10,length).toString().slice(length-1) + 
            Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
        return randomNum;
    }
    

    This will basically add 0's at the beginning to make the length of the number as required.

    0 讨论(0)
提交回复
热议问题