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. 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.
Math.ceil() - rounds to a larger number.
We pull the number to the ceiling.
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().
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.
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.
Top comments (0)