How can you implement a rounding function which will round all numbers as usual except 0.5 or any odd multiple of it down to the nearest integer?
For example:
2.899
is to be rounded up to 3.0
2.332
is to be rounded down to 2.0
2.5
is also to be rounded down to 2.0
(and NOT 3.0
)You can use BigDecimal
as follows:
public static double roundHalfDown(double d) {
return new BigDecimal(d)
.setScale(0, RoundingMode.HALF_DOWN)
.doubleValue();
}
Example:
for (double d : new double[] { 2.889, 2.332, 2.5 }) {
System.out.printf("%.2f -> %.2f%n", d, roundHalfDown(d));
}
Output:
2.89 -> 3.00
2.33 -> 2.00
2.50 -> 2.00