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

Can't I just use Math.round() and it will round to the nearest int, instead of using .ceil() and .floor()

Can't I just use Math.round() and it will round to the nearest int, instead of using .ceil() and .floor() . I used it in a random number guessing game and it seemed to work just fine, I set it to a random number 1 - 10 and I got every number from 1 - 10...

1 Answer

This is more of a math question than javascript. If you have 1.55872 and wish to round it then you will get 2 (because the least amount of change to that number to reach a whole number. is going to be up). If you wish to round it down then you will also get a 1. If you wish to round it up however. You will get 2.

For your specific number guessing game it should work fine with .round. It might not for other applications. If you want to do a Hair cross for a shooting game and wish to make a "auto aim" then you would want to round it appropriately.

==================================

let randNumber = Math.random() * 100; //My generated number is 67.9737660771872.

Math.round(randNumber); //gets me 68

Math.ceil(randNumber); // gets me 68

Math.floor(randNumber); // gets me 67

Okay, I can see when you need to use the floor or ceil, but for the game I can see why round is fine to use. Thank you for putting it into visual perspective for me.