Coding Newbie

Difference between Math.round() and Math.ceil() methods in JavaScript

In this article we will go through the two inbuilt JavaScript methods and basic difference between Math.round() and Math.ceil().

Both Math.round() and Math.ceil() refer to rounding off a number to its nearest integer. However, there is a difference in the way these methods behave. To be more precise, they differ when it comes to the direction of rounding. Let’s walk through both of these methods.

If you are interested to learn about JavaScript array methods, you are more than welcome to read more about them Most Important JavaScript Array Methods.

Math.round()

Math.round() method rounds off a number passed as parameter to its nearest integer, but always in a way to get a lower value of the number passed as parameter.

Syntax:

Math.round(number)

If we look at the example bellow, when a number 9.28 passed as a parameter, Math.round() rounded it to 9, which is a lower value than actual number.

console.log(Math.round(9.28));
// output is a number 9

Math.ceil()

Math.ceil() behaves a bit differently.

Math.ceil() method rounds off the number passed as parameter to its nearest integer, but in order to get a greater value of the number.

Syntax:

Math.ceil(number)

In the below example when a number 9.28 passed as a parameter, Math.ceil() rounded it to 10, which is a greater value than actual number.

console.log(Math.ceil(9.28));
// output is a number 10

Conclusion

In this article we have learned what is the difference between two inbuilt JavaScript methods: Math.round() and Math.ceil().

Both of these methods have wide use in JavaScript, and which one you will use depends solely on the need of your code.

%d bloggers like this: