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 trialSam johnson
Courses Plus Student 688 PointsIs this Ok?
alert("Roll a dice?"); var random = parseInt(Math.random() * 7); alert(random);
It worked but is it a good practice?
Thank you
3 Answers
KRIS NIKOLAISEN
54,971 PointsMath.random()*6 returns a random number between 0 (inclusive), and 6 (exclusive). So 0 to 5.99999999....
Math.floor() makes this 0 to 5.
Adding 1 makes it 1 to 6.
Ar33ss Leon
4,621 PointsI used this
var providedNumber = prompt("Provide a number limit");
document.write(Math.ceil(Math.random() * providedNumber));
KRIS NIKOLAISEN
54,971 PointsIf you want to roll a die your valid values are 1 to 6. What you have above also includes 0 as a possible outcome. You will want to use the standard formula instead:
Math.floor(Math.random() * 6) + 1;
Sam johnson
Courses Plus Student 688 PointsBut 6+1 is the same as 7 right? Or am i missing something?
Sam johnson
Courses Plus Student 688 PointsSam johnson
Courses Plus Student 688 Pointsoh ok Thanks