DEV Community

Shivang Chauhan
Shivang Chauhan

Posted on • Originally published at devswisdom.com on

Javascript Math floor(), Math ceil() and Math round()

Introduction

In javascript there are many ways to round a number, one of the methods is to use a built-in object called Math which gives us three methods to use, Javascript Math.floor(), Math.ceil() and Math.round(), each of these methods serve their purpose and should not be confused with each other or alternatives for each other, in this post, we will try to see how each method works with different examples and which one is suitable for which case.

Math.floor()

This method returns us the largest integer less than or equal to the number which we pass as the input to the method.

Examples

console.log(Math.floor(5.95)); // output: 5

console.log(Math.floor(-11.23)); // output: -12

console.log(Math.floor(9.78)); // output: 9
Enter fullscreen mode Exit fullscreen mode

Math.ceil()

This method returns us the smallest integer greater than or equal to the number which we pass as the input to the method, which means it rounds up the number to the next greater or equal integer.

Examples

console.log(Math.ceil(5.95)); // output: 6

console.log(Math.ceil(-11.23)); // output: -11

console.log(Math.ceil(9.78)); // output: 10
Enter fullscreen mode Exit fullscreen mode

Math.round()

This method returns us the number rounded to the nearest integer, the question may arise that is this going to round up or round down to get to the nearest integer, this depends on the fractional part of the number, so if the fractional part is greater than 0.5 then the number is rounded up and if the fractional part is less than 0.5 then this method rounds down the number and if it is equal to the number than it also rounds up the number.

Examples

console.log(Math.round(5.95)); // output: 6

console.log(Math.round(5.23)); // output: 5

console.log(Math.round(-15.5)); // output: -15
Enter fullscreen mode Exit fullscreen mode

Conclusion

So now it is clear that these methods are different and cannot be used as an alternative for each other, we need to use each one according to our use case.

Check out some more posts from DevsWisdom

What is AWS Artifact?

How to extract text from an image with AWS Textract?

Most Common Methods Used In Javascript and FAQ

AWS Cognito Authentication With Serverless and NodeJS

The post Javascript Math floor(), Math ceil() and Math round() appeared first on DevsWisdom.

Top comments (0)