Get random number within specific range

These two functions are going to return a number that are in the range you specified as arguments.


Libraries

Code Snippet
// Min is inclusive, max is exclusive.
function getRandomFloat(min, max) {
    return Math.random() * (max - min) + min;
}


// Same as above.
// Min is inclusive, max is exclusive.
function getRandomInt(min, max) {
    return parseInt(Math.random() * (max - min)) + min;
}


Implementation

Use for example getRandomInt(1,11) to get a random integer between 1 (inclusive) and 11 (exclusive). In my tests I got the following results:<code> getRandomInt(1,11); 2 getRandomInt(1,11); 10 getRandomInt(1,11); 9 getRandomInt(1,11); 10 getRandomInt(1,11); 3 getRandomInt(1,11); 2 getRandomInt(1,11); 4 getRandomInt(1,11); 7</code>





Comments
  • mode_editWrite a comment



  • forumComments




Embed Code

We provide special containers which include the full snippet and a link to this site. So for example when you make a tutorial and you are using code from this site, you can use one of the following snippet embeddings:

Load Preview Get Code Close Preview







    Share
    Rating
    thumb_up 1 thumb_down
    Author
    Thorolus

    I'm the head developer and co-founder of GlovilGames Studios (glovilgames.com) and other platforms GlovilGames created, like vsnippets.com, worth-calculator.net, python-obfuscator.com and some mobile apps and games.

    Tags
    Random
    Basics



    Informations

    posted on 2016-09-28 13:32:49

    viewed 99 times

    snippet's UUID is 57ebaa6165d8e

    Similar Snippets