So I am confused why we use Math.floor()
for creating random numbers versus Math.round()
or Math.ceil()
.
For example:
var enemyNumber = Math.floor(Math.random() * 4);
Why don't we use var enemyNumber = Math.ceil(Math.random() * 4);
or var enemyNumber = Math.ceil(Math.random() * 4);
The numbers from Math.random()
are in the range 0 (inclusive) to 1 (exclusive). That means you might get a 0, but you'll never get 1.
Thus that formula starts off with multiplying by an integer, which in your example will give a value from 0 (inclusive) up to 4 (exclusive). If you want random integers like 0, 1, 2, and 3, you have to use .floor()
to get rid of any fractional part entirely. In other words, you might get 3.999, and you don't want a 4, so .floor()
throws away the .999 and you're left with 3.
Now this presumes that what you want is what most people want, a random integer between a minimum value and a maximum value. Once you understand what Math.random()
returns, you're free to generate integers however you want.