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?
Pass the MathContext as the second argument to each call to divide, e.g.
bMileage.divide(new BigDecimal(12), precision)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With