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 trialAnthony Rice
7,976 PointsMath.round as an alternative to Math.floor or Math.ceil?
I was just wondering if using Math.round is a viable alternative to using the Math.round or Math.floor functions for creating a random number generator. My code is as follows
function randomNumber(min, max) {
return Math.round(Math.random() * (max - min)) + min;
}
document.write(randomNumber(99,100) + "<br />");
2 Answers
Matthew Batman
30,187 Pointsmath.ceil
and math.floor
round in a specific direction (up and down), while math.round
will round "accurately." So, math.round
could give you a "0" in instances where math.ceil
could give you a "1" (ie. if the input was 0.4).
Bryan Peters
11,996 PointsWhen used with the random number generator, Math.round will skew your distribution. More info here
Jose Laverde
3,575 PointsJose Laverde
3,575 PointsGood answer. I would just add that you should say "in instances where math.ceil WILL give you a '1'..."
This sounds less ambiguious.