Search code examples
javaroundingbigdecimal

round BigDecimal to nearest 5 cents


I'm trying to figure out how to round a monetary amount upwards to the nearest 5 cents. The following shows my expected results

1.03     => 1.05
1.051    => 1.10
1.05     => 1.05
1.900001 => 1.10

I need the result to be have a precision of 2 (as shown above).

Update

Following the advice below, the best I could do is this

    BigDecimal amount = new BigDecimal(990.49)

    // To round to the nearest .05, multiply by 20, round to the nearest integer, then divide by 20
   def result =  new BigDecimal(Math.ceil(amount.doubleValue() * 20) / 20)
   result.setScale(2, RoundingMode.HALF_UP)

I'm not convinced this is 100% kosher - I'm concerned precision could be lost when converting to and from doubles. However, it's the best I've come up with so far and seems to work.


Solution

  • You can use plain double to do this.

    double amount = 990.49;
    double rounded = ((double) (long) (amount * 20 + 0.5)) / 20;
    

    EDIT: for negative numbers you need to subtract 0.5