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?
BigDecimal
for precise results, you should avoid having anyfloat
ordouble
values of any kind in that code. You already createprice
correctly (using a String literal), I suggest you use the same approach for the interest rate and get rid of thedouble.interestRate
.