How to Round Down or Up a Number in Java

Overview

1. Introduction

This post will show you how to round up or down a number in Java using the Math.ceil and Math.floor functions.

2. Round Up a Number

To round up a number, we can use the Math.ceil function. The Math.ceil receives a number and returns the smallest double value greater than or equal to the provided number. Let's check that with one example:

1  public static void main(String[] args) {
2    System.out.println(Math.ceil(5.55)); // -> 6.0
3    System.out.println(Math.ceil(-5.55)); // -> -5.0
4    System.out.println(Math.ceil(3.0005)); // -> 4.0
5    System.out.println(Math.ceil(-0.0005)); // -> -0.0
6  }

Suppose the provided number is positive and has any floating point. The functions round it up to the next double without a floating point. That happens with 5.55, which turns 6.0, and 3.0005 to 4.0.

For negative numbers, the rule is quite the same. For instance, the function rounds up -5.55 to -5.0 because -5.0 is the next double without a floating point bigger than -5.55.

The exceptional case is for a value less than zero but greater than -1.0. In this case, the result is -0.0 and not 0.0 as expected.

3. Round Down a Number

To round down a number, we can pass it to the Math.floor function. That function returns the biggest double value that is smaller than or equal to the provided number. Let's try one example:

1  public static void main(String[] args) {
2    System.out.println(Math.floor(5.55)); // -> 5.0
3    System.out.println(Math.floor(-5.55)); // -> -6.0
4    System.out.println(Math.floor(1.00055)); // -> 1.0
5    System.out.println(Math.floor(-0.35)); // -> -1.0
6  }

This function works similarly to the ceil function but returns the next double without a floating point right before the value passed as an argument. So, for example, 5.55 and 1.00055 are rounded to 5.0 and 1.0, respectively. In the same way, ceil rounds -5.55 and -0.35 to -6.0 and -1.0, respectively.

4. Identity Function

Both ceil and floor functions have the same identity function: if the value is equal to NaN, infinity, -0.0, 0.0, or any integer, then both functions return the same value provided as an argument.

5. Conclusion

In this post, we've learned how to round down or up a number in our Java application using the floor and ceil functions.