📜  math ceil floor - Javascript (1)

📅  最后修改于: 2023-12-03 15:32:50.390000             🧑  作者: Mango

Math.ceil and Math.floor in JavaScript

In JavaScript, the Math object provides two methods for rounding numbers: Math.ceil() and Math.floor(). Both methods take a single argument, which is the number to be rounded.

Math.ceil()

Math.ceil() rounds a number up to the next integer. It returns the smallest integer greater than or equal to the input number.

Math.ceil(4.2); // returns 5
Math.ceil(-3.8); // returns -3
Math.floor()

Math.floor() rounds a number down to the previous integer. It returns the largest integer less than or equal to the input number.

Math.floor(4.2); // returns 4
Math.floor(-3.8); // returns -4
Comparison

The main difference between Math.ceil() and Math.floor() is the direction in which they round the number. Math.ceil() rounds up, while Math.floor() rounds down.

Math.ceil(4.2); // 5
Math.floor(4.2); // 4
Why use Math.ceil() and Math.floor()?

These methods are useful for a variety of scenarios, such as:

  • Truncating decimal places.
  • Ensuring that a number is rounded in a particular direction.
  • Determining the boundaries of a range.
Conclusion

Math.ceil() and Math.floor() are both useful methods for rounding numbers in JavaScript. They can help you truncate decimal places, round a number in a specific direction, and determine the boundaries of a range.