# What are the differences between JavaScript's Math.floor() and Math.ceil()?Ava Wconst t="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;if(t){const t=document.querySelectorAll("img[data-main-image]");for(let e of t){e.dataset.src&&(e.setAttribute("src",e.dataset.src),e.removeAttribute("data-src")),e.dataset.srcset&&(e.setAttribute("srcset",e.dataset.srcset),e.removeAttribute("data-srcset"));const t=e.parentNode.querySelectorAll("source[data-srcset]");for(let e of t)e.setAttribute("srcset",e.dataset.srcset),e.removeAttribute("data-srcset");e.complete&&(e.style.opacity=1,e.parentNode.parentNode.querySelector("[data-placeholder-image]").style.opacity=0)}}

JavaScript'sMath.floor() andMath.ceil() are both methods of theMath object used for rounding numbers. Here are the differences between these two methods: 1.Math.floor(): - TheMath.floor() method rounds a number down to the nearest integer less than or equal to the given value. - It always returns the largest integer less than or equal to the input value.

1
2
3
4

Math.floor(4.9); // 4
Math.floor(-2.1); // -3

In the first example,Math.floor(4.9) returns4 because4 is the largest integer less than or equal to4.9. In the second example,Math.floor(-2.1) returns-3 because-3 is the largest integer less than or equal to-2.1. 2.Math.ceil(): - TheMath.ceil() method rounds a number up to the nearest integer greater than or equal to the given value. - It always returns the smallest integer greater than or equal to the input value.

1
2
3
4

Math.ceil(4.9); // 5
Math.ceil(-2.1); // -2

In the first example,Math.ceil(4.9) returns5 because5 is the smallest integer greater than or equal to4.9. In the second example,Math.ceil(-2.1) returns-2 because-2 is the smallest integer greater than or equal to-2.1. 3. Usage scenarios: -Math.floor() is commonly used when you need to round down a number to the nearest integer. It is useful in situations like calculating array indices or truncating decimal places. -Math.ceil() is often used when you want to round up a number to the nearest integer. It is useful, for example, in calculations where you need to ensure that a value is not rounded down. 4. Comparison: - When dealing with positive numbers,Math.floor() always rounds towards zero (downward), whileMath.ceil() always rounds away from zero (upward). - For negative numbers, the behavior is inverted.Math.floor() rounds further away from zero (more negative), andMath.ceil() rounds closer to zero (less negative).

1
2
3
4

Math.floor(-3.5); // -4
Math.ceil(-3.5); // -3

In this example,Math.floor(-3.5) returns-4 because it rounds further away from zero, whileMath.ceil(-3.5) returns-3 because it rounds closer to zero. Choose the appropriate method based on your rounding needs. If you want to round down to the nearest integer, useMath.floor(). If you need to round up to the nearest integer, useMath.ceil().