Rounding in Java – Math.Round, Math.Floor, Math.Ceil

We have decimal values in java, but sometimes there is a need to round them. It is important to remember which function should be used according to the requirements. So In this blog, I will be sharing some ways to round off decimal values in java.

Checking whether java rounds the value up or down by default.

Output:

Explanation:

We are taking two values val1 and val2 from the user as inputs. Then we are dividing both of them and find whether the result will be rounded up or down. Since we are not using any function so the output will be the default result produced in Java while performing division. As an example the val1 is taken as 15 and val2 is taken as 4. The result which has come is 3, through this observation we can conclude that java rounds down by default.

Using Math.Ceil Function for Rounding Value Up

Output:

Explanation:

We are taking a decimal value from the user as input. The Math.ceil() function is used to round up this decimal value. As an example 45.02 is rounded to 46.0.

Using Math.Floor Function for Rounding Value Down

Output:

Explanation:

We are taking a decimal value from the user as input. The Math.floor() function is used to round down this decimal value. As an example 45.99 is rounded to 45.0.

Using Math.Round Function for Rounding to Nearest Value

Output:

Explanation:

We are taking a decimal value from the user as input. The Math.floor() function is used to round this decimal value to its nearest decimal number. As an example 45.51 is rounded to 46.0. Similarly 45.49, 45.50 will round to 45.0, 46.0.

Conclusion

Do remember that after rounding the value either up or down, the value will still be a decimal number in all the above cases.

So these were the ways of rounding a number in java. Please feel free to ask your doubts in the comment section of this blog.

Leave a Reply

Your email address will not be published. Required fields are marked *