Let's talk about Math.ceil, Math.floor, and Math.round 🌿

Subscribe to my newsletter and never miss my upcoming articles

Introduction

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 all know JavaScript has a built-in object called Math, which has properties and methods for mathematical constants and functions.

We have three methods that are mostly used to round off a number in JS, i.e., Math.ceil(), Math.floor(), Math.round(). Let's explore them in this article.

ğŸŽ³ Math.ceil

Math.ceil function in JavaScript is used to round of a number that is passed into it to its nearest integer in upward direction of rounding. What to I mean by upward direction? Towards the greater value. 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.floor()

Where the 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()

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.

ğŸŽ³ Math.trunc()

There's another method available in JS Math object that is Math.trunc(). 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

Conclusion

Rounding off numbers is an essential part of programming. I hope this article revisited your memories about different built-in rounding off methods we have in JavaScript. Leave an ❤ if you found this article helpful. 😊

No Comments Yet