JavaScript Random Numbers


Random Numbers

You use the Math.Random() function to generate a number between 0 (inclusive) and 1 (exclusive). You can multiply the result by 7, for example, to get a number between 0 (inclusive) and 7 (exclusive) and then use the Math.Floor() function to remove anything to the right of the decimal.

To get a number between 0 and 6, try the code below.

var rand1 = Math.floor(Math.random() * 7);

To get a number between 1 and 10, try the code below.

var rand1 = 1 + (Math.floor(Math.random() * 10));

General Formula

To get a number between x and y, where you provide the numbers for x and y and the following conditions are met:

  • the numbers x an y have no fractional parts
  • x is less than y
  • the two numbers may be negative or positive

Try the code below. As an example, if you want a random integer (no fractional parts) between -3 and -1 (meaning -3, -2 or -1) then x = -3 and y = -1. Be careful when you substitute a negative value for x into (y + 1 – x) because x will become positive in this case because subtracting a negative number means you need to add it.

var rand1 = x + (Math.floor(Math.random() * (y + 1 - x)));

Exclusive

To get a number between 1 and 3 (exclusive) with two decimal places, try the code below.

var rand1 = (1 + (Math.floor(Math.random() * 2))) + Math.random();

Math.floor()

Floor() rounds a number downward to its nearest integer. An integer has no fractional part and can be zero, negative or positive. Therefore Math.floor(-1.6) will return -2.