Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Working With Numbers Create a random number

Ignacio Van Humbeeck
Ignacio Van Humbeeck
2,150 Points

Why not simply use Math.round? I test it and it also gives me 6 sometimes

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

2 Answers

The answer is basically the same as why not use Math.ceil():

As the transcript says: Now you might be wondering why we don't just use the Math.ceil method. 4:45 It rounds upwards, so a number over five would round up to six. 4:50 It seems like a good idea, and might make it so that we don't have to 4:53 add one at the end of the statement to produce a number from one to six. 4:58 Unfortunately, there's a slight chance you'll end up with a zero. 5:02 Remember, the Math.random method returns a number from zero up to one. 5:10 The random number can actually be zero. 5:12 In this case using Math.ceil on zero returns zero. 5:18 So, if we did use Math.ceil, we could end up with numbers from zero up to and 5:23 including six.

There would be an equally slight chance that Math.round() could also yield a zero.
Julie Kohler
Julie Kohler
6,122 Points

Thank you, jcorum! That confused me as well.

I'm a noob so pardon if my interpretation isn't correct. I guess the reason Math.ceil() is not advisable to use for a 6-dice roll is because there is a chance that it will return a 7? For example, if Math.random gives us 5.1, then that will be 6 right? Now when you perform the Math.ceil(5.1) + 1, that would give you 7, and 7 is not included in a 6-dice roll. Also, even if you get a 0 from Math.ceil, remember that it will be added to 1 right, so a Math.ceil(0) + 1 will give you 1, which is still inside the 6-dice roll.

I tried Math.ceil(Math.random() * 6) + 1; and it always gives me rolls between 2 and 7.

So to keep it simple, Math.ceil gives you a dice roll range of 2 to 7.

Hope that helps.

Peter Retvari
Peter Retvari
2,566 Points

I believe it's all about add 1 to the random number function, cause without this it could be end up with zero. and after we added 1 we have to use the floor function as well. Am I right?