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 Create a random number

Juan David Hernandez
Juan David Hernandez
7,415 Points

Why don't we use parsefloat() instead Math.floor()?

So,I have something like:

var question = parsefloat(Math.Radom() * 6 + 1);

alert("I have" + question);

If the code runs inside out when the first parts is done we should have a decimal random number and then parsefloat would does the rest but it doesn't work and I don't know why.

Could you tell me why?

Tony Martin
Tony Martin
5,570 Points

parseFloat() returns a floating point number whereas Math.floor() will return the whole integer rounded down.

The purpose of using Math.floor() is to get back a whole number, not a decimal. In this example, we don't want a decimal, which parseFloat would give us.

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

parseFloat() will return the same number that went in since the the decimal point is a valid part of a floating point number. Perhaps you mean parseInt() instead? Two reasons I can think of:

  • With Math.floor() the function does exactly when you want it to do, drop the digits after the decimal place. parseInt() turns strings into numbers and you're relying on a side-effect to do what you want. Math.floor() makes your intentions clear to anyone reading the code.

  • parseInt() has a hidden cost. It takes a string argument but you're passing it a number. The number you input will get converted to a string automatically, so it can be converted back to a number. This is much less efficient than Math.floor().

Juan David Hernandez
Juan David Hernandez
7,415 Points

yes, I meant parseint(). Thanks for your time, you're right!