Let's talk about Math.ceil, Math.floor, and Math.round 🌿
2 min read
We all have learned about rounding off numbers in our school. We usually increase the integer if its value is >=.5 and decrease it, if it is <= .4.
1.5 ≈ 2
1.4 ≈ 1
We have three methods that are mostly used to round off a number in JS, i.e.,
Math.round(). Let's explore them in this article.
Math.ceil() takes only one parameter that is the value to be rounded. So, if we have a value of 1.4,
Math.ceil() will round off it to 2.
console.log(Math.ceil(1.4)); //2 console.log(Math.ceil(1.6)); // 2 console.log(Math.round(-1.4)); // 1 console.log(Math.round(-1.6)); // 1
Photo from Wikipedia
Math.ceil method returns the smallest integer greater than or equal to the value we pass,
Math.floor returns the largest or equal integer less than the given value. It also takes a single parameter.
Photo from Wikipedia
So, if we pass the same value 1.4 in
Math.floor, we'll get 1 in return. Even if we pass 1.6, we'll also get 1.
console.log(Math.floor(1.4)); // 1 console.log(Math.floor(1.6)); // 1 console.log(Math.floor(-1.4)); // -2 console.log(Math.floor(-1.6)); // -2
Math.round() rounds off the number depending on the fractional part of the number. So, if the fractional part is >=.5, it'll return the smallest integer greater than the passed value and if the number is <=.4 we'll get the largest integer smaller than the number we pass.
console.log(Math.round(1.4)); // 1 console.log(Math.round(1.6)); // 2 console.log(Math.round(1.5)); // 2 console.log(Math.round(-1.4)); // -1 console.log(Math.round(-1.6)); // -2 console.log(Math.round(-1.5)); // 2
So, Math.round() can go both upward and downward depending on the fractional Part.
There's another method available in JS Math object that is
Math.trunc() returns the integer part of a number by removing any fractional part of the number.
console.log(Math.trunc(1.4)); // 1 console.log(Math.trunc(1.6)); // 1 console.log(Math.trunc(-1.4)); // 1 console.log(Math.trunc(-1.6)); // 1
Did you find this article valuable?
Support Subha Chanda by becoming a sponsor. Any amount is appreciated!