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
Brent Leung1,389 Points
How do we account for users inputting one or two negative numbers?
parseInt() will work just fine with negative numbers.
parseInt(-5) into the console will return -5.
The formula used to generate a random number will also work just fine with negative numbers.
Math.random() returns a number between 0 and 1 (not including 1).
Multiplying that by
(topNumber - bottomNumber + 1) will give a number between 0 and the difference between
bottomNumber + 1, not including
bottomNumber. So if our top and bottom numbers are 10 and 1 respectively, the random number will come out between 0 and 9.9999999...
bottomNumber will raise or lower the entire range so the lowest possible value will be
So looking at the entire example where
bottomNumber = -5 and
topNumber = 7:
- Math.floor(Math.random() * (topNumber - bottomNumber + 1) + bottomNumber)
- = Math.floor(Math.random() * (7 - (-5) + 1) + (-5))
- = Math.floor(Math.random() * (13) + (-5))
- = Math.floor([0 ≤ n < 13]) + (-5)) //Range doesn't include 13
- = Math.floor([0-5 ≤ n < 13-5])
- = Math.floor([-5 ≤ n < 8])
- = [-5 ≤ n ≤ 7] //Everything over 7 gets rounded down