Search code examples
javamathdoublebigdecimal

Is there a cleaner/simpler way for writing this formula in code?


I need to return a double value. This value is derived from this formula.

monthly interest = balance * interest rate / 100.00 /12.0

Due to some precision issues, I am to use BigDecimal during calculation and return a double value (as this is how money is represented).

I've tried the code below and it works perfectly okay but looks quite long and a bit unreadable if you ask me.

double bal = 10, rate=2, hundred = 100.00, month = 12.0;

double monthInt= (BigDecimal.valueOf(bal).multiply(BigDecimal.valueOf(rate)).divide(BigDecimal.valueOf(hundred)).divide(BigDecimal.valueOf(month))).doubleValue();

return monthInt;

Solution

  • You know that the result of balance * interest rate will always be divided by 100 and 12. So you could save these static parts of your formula in a static variable.

    private static final BigDecimal MONTH_IN_PERCENT = BigDecimal.valueOf(100 * 12);
    

    And then use that in your computation:

    return BigDecimal.valueOf(bal).multiply(BigDecimal.valueOf(rate).divide(MONTH_IN_PERCENT).doubleValue();
    

    And if you can guarantee that bal * rate <= Long.MAX_VALUE, you can use this version:

    return BigDecimal.valueOf((long) bal * rate).divide(MONTH_IN_PERCENT).doubleValue();