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

Michael Lambert
Michael Lambert
6,286 Points

My solution with 2 inputs

Is it valid to use Math.round as opposed to Math.floor in my below way of generating a random number between the two inputs?

var firstNumber = parseInt(prompt('Enter your first number'));
var secondNumber = parseInt(prompt('Enter your second number'));
var lowNumber = Math.min(firstNumber, secondNumber);
var highNumber = Math.max(firstNumber, secondNumber);
var randomNumber = Math.round(Math.random() * (highNumber - lowNumber) + lowNumber);
document.write('Number generated between "<b>' + lowNumber + ' and ' + highNumber + '</b>" is <b style=\"color:red\">' + randomNumber + '</b>');
Emmanuel C
Emmanuel C
10,636 Points

Math.floor rounds down to the nearest int, so 3.8 would become 3. Math.round just rounds normally to the nearest int, so 3.8 would be 4.

1 Answer

Michael Lambert
Michael Lambert
6,286 Points

I think i was struggling at first to see an example of when to use one over the other as it seemed both was giving the same results. With some tweaking to my code I now see the benefit of using one over the over.

I wanted to generate a number between the two inputs and not include them. The below code using the Math.round would somtimes return the highest number input but using the Math.floor never seems to do it which is the outcome i was after.

I'm not sure if my code is the best way to achieve the result I'm after but was the only way i could think to achieve it.

var firstNumber = parseInt(prompt('Enter your first number'));
var secondNumber = parseInt(prompt('Enter your second number'));
var lowNumber = Math.min(firstNumber, secondNumber) + 1;
var highNumber = Math.max(firstNumber, secondNumber) - 1;
var randomNumber = Math.round(Math.random() * (highNumber - lowNumber + 1)) + lowNumber;
document.write('Number generated between "<b>' + (lowNumber - 1) + ' and ' + (highNumber + 1) + '</b>" is <b style=\"color:red\">' + randomNumber + '</b>');