# Basic JavaScript - Generate Random Whole Numbers within a Range

Tell us what’s happening:
Describe your issue in detail here.
actually I have finish the challenge successfully but I am still confuse a bit about what this code does

``````Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;

``````

``````function randomRange(myMin, myMax) {
// Only change code below this line
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
// Only change code above this line
}
``````

User Agent is: `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36`

Challenge: Basic JavaScript - Generate Random Whole Numbers within a Range

`random` is a function that generates a number greater than or equal to 0 and less than 1.

So if I pick some numbers that might be generated by `random`:

``````0
0.25
0.5
0.88
``````

(It’ll be more like 0.263578975432… rather than 0.2, but just as an example)

If you want integers, then there are functions for converting a floating point to the closest integer, one of which is `floor`, which converts down to closest integer (as opposed to `ceil` which converts up). Issue is that if you do that on the result of rand:

``````Math.floor(0) // 0
Math.floor(0.2) // 0
Math.floor(0.5) // 0
Math.floor(0.8) // 0
``````

So you could multiply by 10 maybe:

``````Math.floor(0) // 0
Math.floor(2.5) // 2
Math.floor(5) // 5
Math.floor(8.8) // 8
``````

Then you can get the numbers 0…9 (random doesn’t go up to 1)

But what you want is a number between min and max.

So say:

``````myMin = 10
myMax = 20
``````

And then if you multiply by the difference between them (so 20 - 10, so 10), gives you same as above:

``````Math.floor(0 * 10) // 0
Math.floor(0.25 * 10) // 2
Math.floor(0.5 * 10) // 5
Math.floor(0.88 * 10) // 8
``````

Which isn’t right, your `min` is 10. So add the `min` on after you `floor`:

``````Math.floor(0 * 10) + 10 // 10
Math.floor(0.25 * 10) + 10 // 12
Math.floor(0.5 * 10) + 10 // 15
Math.floor(0.88 * 10) + 10 // 18
``````

This is almost there. Issue is, the number can never reach `max`. Soo, just add 1 to the difference that you multiply `random` by:

``````Math.floor(0 * (10 + 1)) + 10 // 10
Math.floor(0.25 * (10 + 1)) + 10 // 12
Math.floor(0.5 * (10 + 1)) + 10 // 15
``````

Those are the same, but then:

``````Math.floor(0.88 * (10 + 1)) + 10 // 19
``````

Now, if `random` was to generate a number greater than 0.9:

``````Math.floor(0.99 * (10 + 1)) + 10 // 20
``````

It can reach 20

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.