Careeroza
Rounding Numbers
round, ceil and floor
| Method | Rule | 4.3 | 4.5 | -4.5 |
|---|---|---|---|---|
Math.round | nearest (half goes up) | 4 | 5 | -4 |
Math.ceil | up to next whole number | 5.0 | 5.0 | -4.0 |
Math.floor | down to previous whole number | 4.0 | 4.0 | -5.0 |
(int) cast | cut off decimals | 4 | 4 | -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.