Java Math.ceil() vs floor() vs round() With Examples

Math.ceil() vs floor() vs round() in Java explained with negative numbers, ties, return types, ceilDiv(), NaN edge cases and a rating example.

Two number line segments showing Math.ceil, Math.floor and Math.round applied to -4.5 and 4.3

In Java, Math.ceil() rounds a number up to the next whole number, Math.floor() rounds it down, and Math.round() rounds it to the nearest whole number, with a tie such as 4.5 going up. The choice of Math.ceil() vs floor() vs round() comes down to the direction each method moves the value, where up means toward positive infinity, also for negative numbers.

We use these methods whenever a fractional value must become a whole number, for example to count pages, boxes or seats, to show a rating or to turn a measured value into an index.

The following example rounds the same kind of values with all three methods.

double up = Math.ceil(4.3);             // 5.0
double down = Math.floor(4.9);          // 4.0
long nearest = Math.round(4.5);         // 5
long negativeTie = Math.round(-4.5);    // -4
double negativeUp = Math.ceil(-4.3);    // -4.0

Notice that ceil() and floor() return a double while round() returns a long, and that -4.5 rounds to -4, not -5. We go through each method, compare them in one table, and cover integer division with ceilDiv(), the edge cases with NaN and very large values, and rounding to decimal places.

1. Using Math.ceil() for Rounding Up a Number

The Math.ceil() method returns the smallest whole number that is greater than or equal to the argument. Any fractional part, even 0.0001, moves the value up to the next whole number, and a value that is already whole stays as it is.

In the following example, Math.ceil(4.3) rounds 4.3 up to 5.0, so the result is never less than the original number. The result is a double, and 5.0 is mathematically equal to the integer 5.

double number = 4.3;
double roundedUp = Math.ceil(number);   // 5.0
double whole = Math.ceil(7.0);          // 7.0
double tiny = Math.ceil(7.0001);        // 8.0
double negative = Math.ceil(-4.3);      // -4.0
int pages = (int) Math.ceil(4.3);       // 5

For negative numbers, up still means toward positive infinity, so -4.3 becomes -4.0. We need an explicit cast when we want an int or a long, because the method keeps the double type.

We use Math.ceil() when underestimating would be a bug.

  • Calculating the number of items needed to cover an area or a distance, such as tiles for a floor or buses for a group.
  • Counting result pages, because 41 recipes at 10 per page still need a fifth page.
  • Billing per started unit, such as a parking lot that charges every started hour.

2. Using Math.floor() for Rounding Down a Number

The Math.floor() method returns the largest whole number that is less than or equal to the argument. It drops the fractional part of a positive number and moves a negative number further away from zero.

In the following example, Math.floor(4.9) rounds 4.9 down to 4.0, so the result is never greater than the original number.

double number = 4.9;
double roundedDown = Math.floor(number);   // 4.0
double negative = Math.floor(-4.3);        // -5.0
int truncated = (int) -4.3;                // -4

The (int) cast is not the same as Math.floor() for negative numbers. A cast from double to int rounds toward zero, so it gives -4 for -4.3, while floor() gives -5.0. For positive numbers both give the same whole number.

We use Math.floor() when overestimating would be a bug.

  • Calculating the number of full containers, such as full egg cartons from a number of eggs.
  • Computing an age in whole years or a level in a game from accumulated points.
  • Mapping a value to a bucket, such as a price of 23.75 to the price band 20 to 30.

3. Using Math.round() for Rounding to the Nearest Integer

The Math.round() method rounds a double or a float to the closest whole number. When the value lies halfway between two whole numbers, the tie goes toward positive infinity, so 4.5 becomes 5 and -4.5 becomes -4. Java does not use round half to even in Math.round(); that rule belongs to Math.rint(), which we cover in section 5.

In the following example, Math.round(4.6) rounds 4.6 to the nearest integer, which is 5.

double number = 4.6;
long rounded = Math.round(number);      // 5

Similarly, Math.round(4.4) rounds 4.4 to the nearest integer, which is 4.

double number = 4.4;
long rounded = Math.round(number);      // 4

The return type depends on the argument type. A double argument returns a long, and a float argument returns an int, so we can assign the float version to an int without a cast.

long fromDouble = Math.round(2.5);      // 3
int fromFloat = Math.round(2.5f);       // 3
long negativeTie = Math.round(-2.5);    // -2
long belowTie = Math.round(-2.51);      // -3
int cast = (int) Math.round(7.8);       // 8

We use Math.round() whenever the closest whole number is the honest answer.

  • Showing a progress bar or a slider value, such as 66.6% shown as 67%.
  • Rounding a statistic for a report, such as an average delivery time of 31.4 minutes shown as 31.
  • Rounding to a fixed step by scaling first, such as half stars for a rating.

The Math.round() method always returns a whole number. For prices and other values with decimal places, rounding to N decimal places with BigDecimal gives exact results, whereas multiplying by 100, rounding and dividing again fails for values such as 1.005.

4. Math.ceil() vs floor() vs round() Compared

All three methods agree on whole numbers and differ only in the direction they move a fractional value. Positive values behave the way most people expect, and negative values show the real rules, because up means toward positive infinity for every method.

Two number line segments showing Math.ceil, Math.floor and Math.round applied to -4.5 and 4.3
The ceil() method moves right, floor() moves left, and round() picks the closer neighbor with ties going right, for negative numbers too

Each row of the table applies the four ways of rounding to one value, plus the (int) cast that many developers use by mistake as a floor.

ValueMath.ceil()Math.floor()Math.round()Math.rint()(int) cast
4.35.04.044.04
4.55.04.054.04
4.75.04.055.04
-4.3-4.0-5.0-4-4.0-4
-4.5-4.0-5.0-4-4.0-4
-4.7-4.0-5.0-5-5.0-4

The return types matter as much as the values. The methods ceil(), floor() and rint() return a double, which we cast when we need an index or a count, whereas round() returns a long for a double argument and an int for a float argument.

double value = -4.5;
double c = Math.ceil(value);            // -4.0
double f = Math.floor(value);           // -5.0
long r = Math.round(value);             // -4
double e = Math.rint(value);            // -4.0
int t = (int) value;                    // -4

5. Math.rint() and Banker’s Rounding

The Math.rint() method also rounds to the closest whole number, but it breaks a tie toward the even neighbor. This rule is called round half to even or banker’s rounding, and it sends half of the ties up and half down, so a sum of many rounded values does not drift upward.

double a = Math.rint(2.5);              // 2.0
double b = Math.rint(3.5);              // 4.0
double c = Math.rint(-2.5);             // -2.0
long d = Math.round(2.5);               // 3

The Math.rint() method returns a double. For money, the same rule is available as RoundingMode.HALF_EVEN on BigDecimal, which is the better choice when the value has decimal places.

6. Rounding Integer Division Up or Down

A common reason to call Math.ceil() is a division of two integers, such as the number of pages for a list of results. The expression Math.ceil(41 / 10) returns 4.0 instead of 5.0, because 41 / 10 is an integer division that already dropped the remainder before ceil() runs.

int recipes = 41;
int perPage = 10;
double wrong = Math.ceil(recipes / perPage);            // 4.0
double viaDouble = Math.ceil((double) recipes / perPage); // 5.0
int pages = Math.ceilDiv(recipes, perPage);              // 5

Since Java 18, Math.ceilDiv() divides two int or long values and rounds the result up without going through double. Its partner Math.floorDiv() (Java 8) rounds down toward negative infinity, whereas the / operator rounds toward zero.

int plain = -7 / 2;                     // -3
int floored = Math.floorDiv(-7, 2);     // -4
int ceiled = Math.ceilDiv(-7, 2);       // -3
int cartons = Math.floorDiv(45, 12);    // 3

Say a recipe app lists 41 recipes with 10 per page. The pagination bar needs Math.ceilDiv(41, 10), which is 5 pages, and the last page shows the remaining recipe. The same app counts full egg cartons for a shopping list with Math.floorDiv(45, 12), which is 3, because a carton with 9 eggs is not full.

7. Edge Cases With NaN, Infinity and Large Values

The three methods never throw an exception, so bad input turns into a valid-looking result. The ceil() and floor() methods return NaN and the infinities unchanged, while round() has to return a long and maps them to fixed values.

double nanCeil = Math.ceil(Double.NaN);               // NaN
long nanRound = Math.round(Double.NaN);               // 0
long hugeRound = Math.round(1e20);                    // 9223372036854775807
long infRound = Math.round(Double.NEGATIVE_INFINITY); // -9223372036854775808
double minusZero = Math.ceil(-0.5);                   // -0.0

A NaN that becomes 0 can hide a division by zero in a report, and a huge value clamps to Long.MAX_VALUE. The last line shows that Math.ceil() returns negative zero for values between -1 and 0, which prints as -0.0 in a label. We check the input with Double.isFinite() before rounding when the value comes from a calculation that can fail.

static long safeRound(double value) {
    if (!Double.isFinite(value)) {
        throw new IllegalArgumentException("Not a finite number: " + value);
    }
    return Math.round(value);
}
long ok = safeRound(31.4);                 // 31
long bad = safeRound(0.0 / 0.0);           // IllegalArgumentException: Not a finite number: NaN

8. Real-World Example With Star Ratings

A recipe app stores the average rating as a double, such as 4.26 from 23 votes, and each screen rounds it with a different rule. The list view shows whole stars, the detail view shows half stars, and a badge appears only for recipes with at least 4 full stars.

double rating = 4.26;
long wholeStars = Math.round(rating);                 // 4
double halfStars = Math.round(rating * 2) / 2.0;      // 4.5
boolean badge = Math.floor(rating) >= 4;              // true

For half stars, we scale the value by 2, round it, and divide by 2.0, so 4.26 becomes 8.52, which rounds to 9 and gives 4.5 after the division. The division must use 2.0 and not 2, otherwise the long result is divided as an integer and the half star disappears.

9. Math.ceil(), floor() and round() FAQs

Negative ties, return types and integer division are the details where these methods give a different answer than a quick mental calculation.

9.1. Why does Math.ceil() return a double and not an int?

The result must cover the whole double range, including values far above Long.MAX_VALUE, NaN and the infinities. An int or long cannot hold these values, so we cast the result ourselves when we know it fits.

9.2. Does Math.round() round half up or half to even?

Java uses a third rule. The Math.round() method rounds a tie toward positive infinity, so 2.5 becomes 3 and -2.5 becomes -2. Round half up in the school sense would give -3. For half to even, we call Math.rint() or use RoundingMode.HALF_EVEN with BigDecimal.

9.3. How do we round a number to 2 decimal places?

The Math.round() method only returns whole numbers, so we either scale the value with Math.round(value * 100) / 100.0 or use BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP). The BigDecimal version also gives 1.01 for 1.005, where the scaling version gives 1.0, so it is the right choice for money.

9.4. Is (int) the same as Math.floor()?

No. The cast rounds toward zero and Math.floor() rounds toward negative infinity. Both give 4 for 4.7, but for -4.7 the cast gives -4 and floor() gives -5.0.

9.5. How do we round an integer division up?

Since Java 18, we call Math.ceilDiv(a, b). On older versions, (a + b – 1) / b works for positive values, and Math.ceil((double) a / b) works when the values fit in a double without losing precision.

10. Conclusion

The three methods differ in direction only. Math.ceil() moves a value toward positive infinity, Math.floor() moves it toward negative infinity, and Math.round() picks the closer whole number, with a tie going toward positive infinity. Negative numbers follow the same rules, which is why -4.5 rounds to -4.

Keep the return types in mind, since ceil() and floor() return a double and round() returns a long or an int. For integer division, Math.ceilDiv() and Math.floorDiv() avoid the double detour, and for decimal places and money, BigDecimal is the safer tool. More number utilities are listed in our Java tutorial.

11. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.