3

I am trying to calculate leaseRate which is a big decial, However I receive the following error: Non-terminating decimal expansion; no exact representable decimal result I see that this is round issue, however I think that I solved this with MathContext precision = new MathContext(2);

I made a small example this issue:

public class Test {
  public static void main(String[] args) {
    MathContext precision = new MathContext(2);
    int mileage = 10;
    int duration = 20;
    BigDecimal price = new BigDecimal("34234.34",precision);
    double interestRate = 4.57;
    BigDecimal bMileage = new BigDecimal(mileage, precision);
    BigDecimal bDuration = new BigDecimal(duration,precision);
    BigDecimal bInterestRate = new BigDecimal(interestRate,precision);
    BigDecimal leaseRate = ((((bMileage.divide(
        new BigDecimal(12,precision))).multiply(bDuration)).divide(
        price)).add(
        ((bInterestRate.divide(new BigDecimal(100,precision))).multiply(
            price)).divide(new BigDecimal(12,precision))));
    System.out.println(leaseRate);
  }
}

What is wrong with my code?

1
  • 3
    Generally speaking when you use BigDecimal for precise results, you should avoid having any float or double values of any kind in that code. You already create price correctly (using a String literal), I suggest you use the same approach for the interest rate and get rid of the double.interestRate. Commented Mar 16, 2023 at 13:46

1 Answer 1

2

Pass the MathContext as the second argument to each call to divide, e.g.

bMileage.divide(new BigDecimal(12), precision)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.