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

JavaScript Being weird

Ok, So I'm wondering why JavaScript uses decimals in its Math.Random() function. I've seen other languages tat use actual Integers and I'm wondering if there is a logical explanation. Was it due to some technological disability back when they invented it or does JavaScript just trying to be different or just plain Weird??

Garrett Carver
Garrett Carver
14,681 Points

I would absolutely attribute this to JavaScript people being weird :p

3 Answers

Kristopher Van Sant
PLUS
Kristopher Van Sant
Courses Plus Student 18,830 Points

Math.random() returns a number ONLY between 0 and 1, therefore it will always be a decimal, unless it does in fact return 0, the number 1 is not included so it will never return it. If you want to get random numbers other than what is between 0 and 1 you'll need to multiply math.random() by a number. For example if you want a random number between 0 and 10, you would do Math.random() * 10. However as you mentioned the number will be a decimal. We use Math.floor and Math.ceil to convert decimal values to integers. So to get an integer, you'd apply math.floor to it, which will round down to the nearest whole number, Math.floor(Math.random() * 10).

I think by having Math.random() limited between 0 to 1 is beneficial because from there "you can scale it to your desired range" as the MDN mentions here. If math.random() was not limited to 1 and then included numbers above that, whether decimals or integers, it would be harder to get your desired results. There are also many many many use cases in programming where you'd want your return number to be a decimal. If it only ever returned integers it would be extremely limiting in what you could do with it.

Anywho, I hope that helps clear things up some! :)

the answer of this question is

1 - || means [ or ]

2- Math.floor will round a decimal number [ down ] no matter what.

3 - Math.ceil will round a decimal number [ up ] no matter what.

all three answers , I hope help .

Thanks so much.