Why would anybody call Math.floor
on a Math.random
result? I've seen it used like:
Math.floor(Math.random() * num);
Can someone explain please?
Math.random
returns a floating-point number between 0 and 1.
Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
Multiplying this by n gives a floating point number between 0 (inclusive) and n (exclusive).
Math.floor
is then used to convert this floating point number to an integer between 0 and n - 1 (inclusive).