Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
221,204 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
221,204 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
221,204 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?