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!
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

Jason Nelson
6,209 PointsrandomNumber question.
In the random number extra credit, I'm stuck on this code:
var input= prompt(" Please type a number");
var topNumber =parseInt(input);
var randomNumber = Math.floor(Math.random()*topNumber)+1;
I'm actually confused on the +1, random can give you anything between 0-1 not including 1. Math.floor rounds down what does the +1 do besides just add 1 to the floor number?
example: Math.floor(0.345)6+1 Math.floor(3.07) 3
Is this correct?
2 Answers

Shawn Flanigan
Courses Plus Student 15,815 PointsJason,
I reformatted your question a bit to show the code properly. To try to answer your question, let's break the process down a bit.
You're right that Math.random()
will give you a number between 0
and 1
, not including 1
(to be more specific, it will return a value between 0
and 0.9999999999999999
).
When you multiply this random number by your topNumber
, you will never actually reach your topNumber
. For example, if your topNumber
is 10
, when you multiply your two numbers, you'll reach a maximum value of 9.999999999999999
.
Since you're using Math.floor()
to round your results down, the maximum value you'll get from this equation is 9
.
Your minimum value will be 0 * 10
, or 0
.
If you're trying to generate a number between 1
and your maxNumber
, adding 1
will do the trick nicely.
Hope this makes sense!

Jason Nelson
6,209 PointsAhh, thanks for the breakdown!