You can multiply by 2
, then round to the nearest 10
, then divide by 2
. The precision is 2
for these BigDecimals
; it may need to be different for BigDecimals
of different scale.
BigDecimal[] bds = {new BigDecimal("64.99"), new BigDecimal("65.01")};
BigDecimal two = new BigDecimal("2");
MathContext mcUp = new MathContext(2, RoundingMode.UP);
MathContext mcDown = new MathContext(2, RoundingMode.DOWN);
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (BigDecimal bd : bds)
{
System.out.println("Test: " + bd);
BigDecimal roundUp5 = bd.multiply(two).round(mcUp).divide(two);
System.out.println("Round up: " + currency.format(roundUp5));
BigDecimal roundDown5 = bd.multiply(two).round(mcDown).divide(two);
System.out.println("Round down: " + currency.format(roundDown5));
}
Output:
Test: 64.99
Round up: $65.00
Round down: $60.00
Test: 65.01
Round up: $70.00
Round down: $65.00