This is probably the one you're most familiar with. It takes any number where the fractional part is below
.5 and rounds down, and takes any value equal to or greater than
.5 and rounds up.
Math.round(0.3); // returns 0 Math.round(0.5); // returns 1 Math.round(0.7); // returns 1
This might not always be the effect you want though. So there are two other falvors.
This will always round down to the nearest whole number, no matter the fractional amount. It brings the values to the 'floor', is an easy way to remember it.
Math.floor(0.1); // returns 0 Math.floor(0.9); // returns 0
Math.ceil() will always round a number up to the nearest whole number. It brings the value to the "ceiling".
Math.ceil(0.1); // returns 1 Math.ceil(0.9); // returns 1
There are no obvious times to recommend when to use one or the other, but it's important to have these in your arsenal for when you might need them!
If you enjoyed this article, sign up here to get new articles whisked straight to your inbox!