Emulate PHP’s Rand() Function in Javascript

Javascript’s random number generator is lacking a lot of power. To create a number between say 0 and 10, you can do this:


number = Math.round(Math.random()*10);

Of course you can modify this slightly to fit your needs, but this should be the basics needed.

Edit: As pointed out, the code I supplied is not very random. If you need true random numbers, the mt_rand function supplied by the good guys at phpjs.org is a great solution.


function mt_rand( min, max ) {
    // Returns a random number from Mersenne Twister
    //
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/mt_rand
    // +   original by: Onno Marsman
    // *     example 1: mt_rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

I would suggest using the above when you need to generate random numbers. You should also check out the rest of phpjs.

This entry was posted in Javascript and tagged , , . Bookmark the permalink.

Comments are closed.