Generate a random number between
and .
Include numbers after the decimal point.

Information for Programmers

JavaScript formula for generating a random number

var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

Math.floor() vs Math.round()

Why use Math.floor() and not Math.round()? As an example, let's say that you want to generate numbers in the range of 0 to 2. If you do Math.round(0.4) you get 0, and if you do Math.round(0.5) you get 1. On the other end of your random range, if you do Math.round(1.4) you get 1, and if you do Math.round(1.5) you get 2.

But this means that you are half as likely of getting 0 and 2 as you are of getting 1. Look at this number line:

|        0         |                  1                    |          2           |

Notice that the space for 0 and 2 is smaller than the space for 1. If you wanted to have an equal chance of getting 0, 1, and 2 using Math.round(), you would have do some manipulation with decimal numbers in your random number formula. However, there is an easier way.

If you use Math.floor() on numbers like 0.4, 1.4, and 2.4 for example, this is the number line that you get:

|                  0                   |                   1                   |                   2                  |

As you can see, each of the three numbers in the 0 to 2 range has the same amount of space on this number line, making each one equally likely when you put a random number into Math.floor().

Page last updated 2014-04-10T22:46:00+02:00