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

Samuel Trejo
Samuel Trejo
4,563 Points

Is it important when you use Math.floor()

e.g. Math.floor(Math.random * (max - min + 1)) + min VS Math.floor(Math.random * (max - min + 1) + min)

In the video he used Math.floor before adding the min number. Would there be any problems using it after adding the min?

1 Answer

Hi

You could do it all together ensuring you follow the order of mathematical calculation. But it also depends on the result you are wanting as the Math.floor() function returns the largest integer less than or equal to a given number, so that might affect your maths.

You may need brackets around the first maths operators on more complex maths:

Where this could go wrong... let's assume min is 1.5 and max is 10.

Let's also assume that the random number was 10 for both of them for the simple sake

var min = 1.5;
var max = 10;

// Math.random is 10 in this example for both
 Math.floor((Math.random() * (max - min + 1)) + min); // returns 96

 Math.floor(Math.random() * (max - min + 1)) + min ; // returns 96.5

In the first example, the Math.floor function returns the largest integer less than or equal to the whole maths calculation, which is 10 multiplied by (10 - 1.5 + 1) is 95 + 1.5 is 96.5, return the integer(whole number) of that which is 96.

In the second example Math.floor function does the same but not the last calculation so, 10 multiplied by (10 - 1.5 + 1) is 95 and then after that returns the integer of 95 its adds 1.5 to the end, returning 96.5