我正在尝试编写一个简单的interestEarned方法,该方法使用当前帐户状态的天数来查看该帐户应收到的年度总利息中的多少。例如,在整个365天里,该帐户的全部利息应为0.1。
但是我在测试过程中遇到以下错误:
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
这是方法:
@Override
public BigDecimal interestEarned(int accountStateNumOfDays) {
MathContext m = new MathContext(2);
BigDecimal amount = sumTransactions();
BigDecimal numOfDays = new BigDecimal(accountStateNumOfDays);
return amount.multiply(proportionOfInterestOwed(checkingAccountInterest, numOfDays), m);
}
@Override
public BigDecimal proportionOfInterestOwed(BigDecimal yearlyInterest, BigDecimal numberOfDays) {
return checkingAccountInterest.multiply(Conversion.doubleToBigDecimalConverter(1).divide(Conversion.doubleToBigDecimalConverter(365)));
}
我认为数学上下文应该限制小数位数。我也尝试过在表达式中插入RoundingMode.HALF_UP,但是下面的测试会返回与结果相同的错误-任何想法?
@Test
public void checkingAccount() {
Bank bank = new Bank();
Account checkingAccount = new CheckingAccount();
Customer bill = new Customer("Bill").openAccount(checkingAccount);
bank.addCustomer(bill);
BigDecimal oneHundred = new BigDecimal(100);
checkingAccount.deposit(oneHundred);
BigDecimal naughtPointOne = new BigDecimal(0.1);
// assertEquals(naughtPointOne, bank.totalInterestPaid(), DOUBLE_DELTA);
Assert.assertEquals(naughtPointOne.ROUND_HALF_EVEN, checkingAccount.interestEarned(365).ROUND_HALF_EVEN, DOUBLE_DELTA);
}