For quite a while now, if I wanted to generate a random number between two other numbers, I'd use the functions written in the `Math.random() MDN docs`

But I never really took the time to understand them. How do they work? I'll explain that, in this article.

#
1. `Math.random()`

, `Math.floor()`

, and `Math.ceil()`

`Math.random()`

is simple! It outputs a random decimal number between 0 to 1.

`Math.floor()`

and `ceil()`

are a little different - they always round down and up, respectively. For example:

```
var firstnum = 1.6
Math.floor(firstnum)
>>> 1
var secondnum = 1.2
Math.ceil(secondnum)
>>> 2
```

# 2. Random Decimals

If you try using `Math.random`

on sites like jsconsole, you'll see it always puts out decimals.

So if whatever you're doing is ok with decimals, you can use a function like this:

```
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
```

How does it work?

Well first, we need the `return`

statement - otherwise the function doesn't do anything.

Next, you have `Math.random() * (max - min)`

. This multiplies the difference between your two numbers by the decimal less than 1 that `Math.random()`

produces. For example, if your range is 1 to 10, than the difference is nine - multiply this by a number less than 1, and it becomes less than nine.

To ensure that you don't get a number out of the range (say, 9 * 0.0007 [which would produce 0.0063 which is less than 1!]), it is then added to the minimum number (in this case, 1).

# 3. Random Integers

Ah, the function that I have copy and pasted the most.

```
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
```

This one's a little more complicated - it returns random whole numbers, or integers. The helpful people at MDN have added a comment saying "The maximum is exclusive and the minimum is inclusive". How does this work? Why use Math.ceil and floor?

Imagine for a moment that you are using the function, and put in 1.2 as the minimum, and 10.6 for the maximum. What kind of numbers would you expect to come out of this function? Any number from 2 to 10. If you were to simply use `Math.round()`

on the minimum and maximum, your bounds would become 1 to 11 - which are too big!

Lastly, we again use `Math.floor`

instead of `Math.round`

or `ceil`

- now that the bounds are from 2 to 10, using Math.round or ceil could result in a 2 being unfairly excluded from the results, or the number 11 being returned.

Helpful? Interesting? Too simple? Well, it's for beginners 😉. Leave a comment!

## Discussion (0)