What are the differences between JavaScript's Math.floor() and Math.ceil() functions?
Benjamin C
TheMath.floor() andMath.ceil() functions in JavaScript are used to round numbers down and up, respectively. Here are the differences between these two functions:
1. Rounding Down (Math.floor()):
- TheMath.floor() function rounds a number down to the nearest integer that is less than or equal to the given value.
- It returns the largest integer less than or equal to the given value.
- For positive numbers, it simply removes the decimal part.
- For negative numbers, it rounds towards negative infinity.
- Example:Math.floor(4.9) returns4,Math.floor(-2.1) returns-3.
2. Rounding Up (Math.ceil()):
- TheMath.ceil() function rounds a number up to the nearest integer that is greater than or equal to the given value.
- It returns the smallest integer greater than or equal to the given value.
- For positive numbers, it rounds towards positive infinity.
- For negative numbers, it simply removes the decimal part.
- Example:Math.ceil(4.1) returns5,Math.ceil(-2.9) returns-2.
In summary, the main difference betweenMath.floor() andMath.ceil() lies in the direction of rounding.Math.floor() always rounds down, whileMath.ceil() always rounds up.