Rounding Numbers

round, ceil and floor

MethodRule4.34.5-4.5
Math.roundnearest (half goes up)45-4
Math.ceilup to next whole number5.05.0-4.0
Math.floordown to previous whole number4.04.0-5.0
(int) castcut off decimals44-4

Example

public class Main {
    public static void main(String[] args) {
        double[] values = {4.3, 4.5, -4.5};
        for (double v : values) {
            System.out.println(v + " -> round " + Math.round(v)
                + ", ceil " + Math.ceil(v)
                + ", floor " + Math.floor(v)
                + ", cast " + (int) v);
        }
    }
}

Output

4.3 -> round 4, ceil 5.0, floor 4.0, cast 4
4.5 -> round 5, ceil 5.0, floor 4.0, cast 4
-4.5 -> round -4, ceil -4.0, floor -5.0, cast -4

Rounding to Decimal Places

Example

Multiply, round, divide; or format the output with printf.

public class Main {
    public static void main(String[] args) {
        double price = 1234.5678;
        double twoPlaces = Math.round(price * 100) / 100.0;
        System.out.println(twoPlaces);
        System.out.printf("%.2f%n", price);
        // pages needed to show 47 products, 10 per page
        int pages = (int) Math.ceil(47 / 10.0);
        System.out.println("Pages: " + pages);
    }
}

Output

1234.57
1234.57
Pages: 5

Tip: Math.ceil(total / pageSize) is the standard way to count pages in pagination. Remember to divide using a double.