How to choose Math.ceil and Math.floor correctly
Table of contents
No headings in the article.
Many times we want to calculate something by dividing operations.But we might get a float value as a result, for example, 5 / 2 = 2.5.
In javascript, we have Math.ceil and Math.floor method to use. They have a huge difference from each other.
The Math.ceil will return the smaller integer number which is greater than the original number, do the roundup. For example, the given number is 1.5, Math. ceil
will return 2. If it is 1.4, will return 2.
As mdn said:The Math.ceil()
static method always rounds up and returns the smaller integer which is greater than or equal to a given number.
The Math.floor
will return the larger number which is less than the given number, round down it.
For example, given number is 2.3, will get 2 as return.
Here are some codes to test.
// Using Math.ceil
console.log(Math.ceil(4.2)); // 5
console.log(Math.ceil(4)); // 4, it is a integer
console.log(Math.ceil(7.8)); // 8
console.log(Math.ceil(-7.8)); // -7, is bigger than the given number
// Using Math.floor
console.log(Math.floor(5.1)); // 5
console.log(Math.floor(115.7)); // 115
console.log(Math.floor(-64)); // -65, is less than the given number
So if you want to discard the decimal part of a float number directly, just use the Math.floor
method.