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 The Random Challenge Solution

Brent Leung
Brent Leung
1,389 Points

Negative Numbers

How do we account for users inputting one or two negative numbers?

1 Answer

Philip Enchin
seal-mask
.a{fill-rule:evenodd;}techdegree
Philip Enchin
Full Stack JavaScript Techdegree Student 24,726 Points

parseInt() will work just fine with negative numbers.

Typing 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 topNumber and 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...

Adding the bottomNumber will raise or lower the entire range so the lowest possible value will be bottomNumber.

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