該類中的 Round 方法用於決定在計算時如何進行捨入,如有需要,可以修改該方法。
在該類的 GetMonthRate 方法中,根據貸款期數(months)來判斷是該筆貸款是短期貸款還是中長期貸款,從而決定應該使用什麼利率。
表示等本息法的 LoanEq 類是從 LoanBase 類中派生的:
using System;
using System.Drawing;
using System.Collections.Generic;
namespace Skyiv.Ben.LoanCalculator
{
// 等本息法
sealed class LoanEq : LoanBase
{
public LoanEq(decimal balance, int months, DateTime date, KeyValuePair<DateTime, PointF>[] rates)
: base(balance, months, date, rates)
{
}
protected override void Calculate(decimal balance, int months, DateTime date, KeyValuePair<DateTime, PointF>[] rates)
{
decimal baseAmount = 0, totalAmount = 0, totalInterest = 0;
decimal monthRate0 = decimal.MinValue, monthAmount = decimal.MinValue;
for (int month = months; month >= 1; month--, date = date.AddMonths(1))
{
var monthRate = GetMonthRate(date, months, rates);
var interest = Round(balance * monthRate);
if (monthRate0 != monthRate) monthAmount = GetMonthAmount(balance, monthRate0 = monthRate, month);
baseAmount = monthAmount - interest;
balance -= baseAmount;
if (month == 1 && balance != 0)
{
baseAmount += balance;
interest -= balance;
balance = 0;
}
totalAmount += monthAmount;
totalInterest += interest;
Table.Rows.Add(new object[] { months - month + 1, date, baseAmount, interest, monthAmount, balance, totalAmount, totalInterest });
}
}
decimal GetMonthAmount(decimal balance, decimal monthRate, int months)
{
double tmp = Math.Pow(1 + (double)monthRate, months);
return Round((decimal)((double)balance * (double)monthRate * tmp / (tmp - 1)));
}
}
}