What is Math.random and Math.floor good for?

Sometimes you want your code to spit out random numbers, because who doesn’t like a random number right? (Looking at you lottery lady)

Math.random ( ) ;

Returns a random number between 0 and 1 (excluded). You can then multiply it by 10, for example, to get a number between 0-10, or by 1000 for even more random number awesomeness.

But what do I want with a number like 78.28473911? This is where the floor comes in!

Math.floor ( ) ;

Math.floor rounds the number down to the largest integer, as in a full number like 1 or 5 or 2078.

So combe the two and add some multiplications and you have yourself a nice little random number machine.

Math.floor (Math.random ( ) * 6 );

This will spit out a random number from the 6 options 0, 1, 2, 3, 4 or 5. I’m writing those out on purpose because my brain always thinks “oh yah, random number between 1 and 6”. But no! It’s 6 random numbers, starting with 0.

Either way, you’ve just programmed a dice! Woot!

So what can we use this random magic for?

  • The obvious: any kind of game, like dice games, chance games (evil gambling dark magic), magic eight balls, what have you.
  • Randomly assigning users to groups.
  • Randomy assigning numbers to users.
  • For math or statistics uses.
  • And anywhere else you want to create some unpredictability, you agent of mayhem!

Leave a comment