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

Why can't we use Math.round instead of Math.floor for the dice roll?

I am working on the create a random number from the java scripts basics course and was wondering why Dave used Math.floor( Math.random() * 6) + 1; instead of Math.round( Math.random() * 6); . it seemed to work fine for me either way just curious if there was a negative to using the latter method, or if it was just to show another method. Thanks in advance for any help!

1 Answer

Steven Parker
Steven Parker
231,269 Points

If you keep "rolling" using your "round" formula, you'll find that you will occasionally roll a "0". The distribution is also not uniform, and the chances of rolling a "0" or a "6" will only be half as likely as rolling one of the other numbers.

By using the "floor" formula, you will get only 1 - 6, and the chances of each number are about even.

Oh gotcha thanks I appreciate the answer!

You are my idol! hahah