//PROCESS: Randomness and rounding

<New code>

//PROCESS: Math.round()
— rounds a number to the nearest integer
//PROCESS: Math.floor()
— rounds a number downward to the nearest integer
//PROCESS: Math.ceil()
— rounds a number upward to the nearest integer

//PROCESS: Math.random()
— creates a random decimal from 0 → 0.99999...

//PROCESS: var dieRoll =Math.ceil( Math.random() * 6 );
— creates a random integer from 1 → 6

Generating random numbers

Generating a random number between 1 → 6 requires you to do the following:

  1. generate a random decimal using Math.random()
  2. multiplying the random integer by 6
  3. rounding the result up to the nearest integer

Generating a random integer using Math.random()

There is a function, Math.random(), that returns a random number between 0 → 0.999999... It is not truly random (you need to use something like reading radioactive decay for that), but it is close enough for our purposes at this point.

Here is what Math.random() returns:

Rounding, Floors, and ceilings

There are often times when you want to normally round a number, and Math.round() will do this for you in the usual way:
2.3 round()s normally to:
5.6 round()s normally to:

Sometimes you want to round down to the nearest integer. Math.floor() will do this for you:
2.3 floor()s down to:
5.6 floor()s down to:

Sometimes you want to round up to the nearest integer. Math.ceil() will do this for you:
2.3 ceil()s up to:
5.6 ceil()s up to:

Rolling a die

Let's say for this example that we are using a six-sided die.

We will start off by generating a random decimal:

Then we need to multiply this number by six in order to simulate a range from 1 → 6.

It still does not look like a die roll from 1 &rarr 6 yet. Sometimes we get numbers less one, and we never get a number equal to 6. The function that we need to shape the results into the proper integers is Math.ceil().

Putting it all together in one line

So if you combine everything into one line, the resulting code is:

What about 3 options? 5? 200?

Common mistakes

Learn more