Home >Web Front-end >JS Tutorial >Math.ceil vs Math.floor
Every now and then I come across calls to the ceil and floor methods, belonging to Math. Both methods aim to round a floating point number to an integer number. However, a question that always comes to me, almost automatically, is:
After all, would there be any way to visually compare the logic of these two functions?
Good... Let me try.
Let's imagine that there is a graph in which we can place each argument passed to these functions:
It has the function of rounding a number to the nearest integer value, greater than or equal to (>=) the current number.
Looking at the number inserted in the graph above, what would be the closest integer >= to 1.3? The number 2, of course!
Looking at the number inserted in the graph above, what would be the closest integer >= to -2.001? Since we are now dealing with a negative scale, the next integer >= is -2.
It has the function of rounding a number to the nearest integer value, less than or equal (<=) to the current number. In short, it works the same as Math.ceil, but in the opposite direction on the graph.
Looking at the number inserted in the graph above, what would be the closest integer <= to 1.3? The number 1, of course!
Looking at the number inserted in the graph above, what would be the closest integer <= to -2.001? Since we are now dealing with a negative scale, the next integer <= is -3.
Thus, analyzing the sense of rounding these functions and taking the graph into consideration, we have:
Remembering concepts using images (like the one mentioned above) usually helps me a lot in fixing them. ?
...
The above is the detailed content of Math.ceil vs Math.floor. For more information, please follow other related articles on the PHP Chinese website!