Love Frontend
Community of frontend developers
RU

How to remember the ways of rounding a number to an integer? [ru]

Publication date: 05.11.2019

There are 4 methods of the global Math object, which are used for rounding numbers to an integer: Math.floor(), Math.ceil(), Math.round() and Math.trunc()

The article provides visual examples for better memorization and a small test at the end, to test your knowledge. Let's start with the most (in my opinion) logical ones: Math.floor() and Math.ceil() which have very descriptive names. The meaning of these words already gives us a huge clue for remembering the way each method works.

Math.floor() - rounds to a smaller integer number. It means, that we always press the number to the floor.

how Math.floor() works

Math.ceil() - rounds to a larger number. We pull the number to the ceiling.

how Math.ceil() works

In everyday life, we are used to round numbers based on the proximity of a fractional value to the whole. Proximity for us is determined by half of the number. That is, if the fractional value of the number has exceeded 0.5, then we can say that it is about 1. Half in our case is a barrier that can be used to round up a number to a larger one.

Just for this more humanly correct rounding, JS has the next tool for rounding numbers Math.round().

how Math.round() works

But pay special attention to the negative and positive half. If we have reached exactly half the positive number, then we will round the number to the next larger number on the scale to the right. We will also do the same with a negative number. We will round it to a larger number. Math.round(-2.5) // -2. That is, seeing half of our number we will move to the right (to a larger number).

And the last, incredibly easy to understand method: Math.trunc(). The method simply returns an integer, discarding the fractional part. You can simply imagine that the number is not rounded, but loses its fractional part and you will not be mistaken.

how Math.trunc() works

Math.trunc() does not work in browsers prior to IE10. But there is a very easy polyfill.

if (!Math.trunc) {
Math.trunc = function(v) {
v = +v;
return (v - v % 1) || (!isFinite(v) || v === 0 ? v : v < 0 ? -0 : 0);
};
}

You can also use the prototype methods of Number: toFixed() and toPrecision(), but remember that these are not methods of the built-in Math object and they return a string, not a number.

Could you immediately without cheating understand how this or that number is rounded up? Enter the rounding result in the field and press enter or the "next" button. 12 questions.


Дальше

Enter your email to subscribe on news