Home > Web Front-end > JS Tutorial > body text

Math.ceil vs Math.floor

Barbara Streisand
Release: 2024-11-17 19:34:01
Original
846 people have browsed it

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:

Math.ceil vs Math.floor

Math.ceil(num)

It has the function of rounding a number to the nearest integer value, greater than or equal to (>=) the current number.

num === 1.3

Math.ceil vs Math.floor

Looking at the number inserted in the graph above, what would be the closest integer >= to 1.3? The number 2, of course!

num === -2,001

Math.ceil vs Math.floor

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.

Math.floor(num)

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.

num === 1.3

Math.ceil vs Math.floor

Looking at the number inserted in the graph above, what would be the closest integer <= to 1.3? The number 1, of course!

num === -2,001

Math.ceil vs Math.floor

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:

Math.ceil vs Math.floor

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template