Why would I combine Math.floor with Math.random?

Aziz Al-ghannam picture Aziz Al-ghannam · Nov 3, 2011 · Viewed 23.9k times · Source

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?

Answer

Mark Byers picture Mark Byers · Nov 3, 2011

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).