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

Adam Maley
Adam Maley
5,946 Points

Using Math.Ceil instead of Math.floor?

Math.floor(Math.random() * 6) + 1 How would this ever result in 0 like he said ?

the + 1 at the end would stop this from happening?

2 Answers

Tina Gee
Tina Gee
3,296 Points

If you test Math.ceil() and Math.floor() in the console, it'll make a bit more sense.

For example, Math.ceil(-0.001) returns -0. Math.floor(-0.001) returns -1.

Since we are working with rolling dice and dice have sides 1 through 6 but never a 0 side, we will want to use Math.floor() because it will prevent us from having to deal with the possibility of Math.ceil returning a 0.

Steven Parker
Steven Parker
231,236 Points

That's not quite right. Both Math.floor and Math.ceil could return a 0. But Math.floor gives you the same chances of getting each possible value.

Swedina Yolanda
Swedina Yolanda
931 Points

It's said that Math.random returns a random number in the range from 0 up to 1, so I'm kinda confused with the -0.001 example.

Steven Parker
Steven Parker
231,236 Points

You're right, Swedina, that's not an example of a value you could get from "Math.random". But it does illustrate the difference between "Math.ceil" and "Math.floor".

A better example might be the value "0.5".

Steven Parker
Steven Parker
231,236 Points

It might result in 0 before the 1 was added.

Using Math.Ceil would not help the case where the value was actually zero.

I believe the possibility of the result of the formula being 0 was discussed as the reason to add 1 to it. If you heard otherwise, can you give a specific time reference in the video for where it is said?