My mortgage calculator is working fine except for the first month.
I have created a codepen for testing. For example, the start date is this month, this year. The loan amount is 300,000, the interest rate is 3% and the term is 30 years.
Month 1 balance should be the total balance minus the Principal but the principal is not getting subtracted until the 2nd month.
function calculate_amortization(loan_amount, monthly_mortgage, monthly_interest_rate, length_of_mortgage) {
var month = parseInt($('#month').val());
var year = parseInt($('#year').val());
var tableData = "<tr> \
<th>Month</th> \
<th>Payment</th> \
<th>Principal</th> \
<th>Interest</th> \
<th>Balance</th> \
</tr>";
// Initializing the empty totals
var total_mortgage = parseFloat(0);
var total_principal = parseFloat(0);
var total_interest = parseFloat(0);
for (i = length_of_mortgage; i > 1; i--) {
var monthly_interest = parseFloat(loan_amount * monthly_interest_rate).toFixed(DIGIT_PRECISION);
var monthly_principal = parseFloat(monthly_mortgage - monthly_interest).toFixed(DIGIT_PRECISION);
total_mortgage = parseFloat(total_mortgage) parseFloat(monthly_mortgage);
total_principal = parseFloat(total_principal) parseFloat(monthly_principal);
total_interest = parseFloat(total_interest) parseFloat(monthly_interest);
// var monthStr = convert_month(month);
var monthStr = convert_month(month);
var tablerow = "<tr> \
<td>" monthStr " " year "</td> \
<td>$" localeString(monthly_mortgage) "</td> \
<td>$" localeString(monthly_principal) "</td> \
<td>$" localeString(monthly_interest) "</td> \
<td>$" localeString(parseFloat(loan_amount).toFixed(DIGIT_PRECISION)) "</td> \
</tr>";
tableData = tableData tablerow;
if (month == 12) {
month = 1;
year ;
}
else {
month ;
};
loan_amount = parseFloat(loan_amount - monthly_principal).toFixed(DIGIT_PRECISION);
};
tablerow = "<tr> \
<td></td> \
<td></td> \
<td><strong>$" localeString(parseFloat(total_mortgage).toFixed(DIGIT_PRECISION)) "</strong></td> \
<td><strong>$" localeString(parseFloat(total_principal).toFixed(DIGIT_PRECISION)) "</strong></td> \
<td><strong>$" localeString(parseFloat(total_interest).toFixed(DIGIT_PRECISION)) "</strong></td> \
</tr>";
tableData = tableData tablerow;
$('h3#amortization-header').html('Amortization Schedule');
$('#total_interest').val(localeString(parseFloat(total_interest).toFixed(DIGIT_PRECISION)));
$('table#amortization').html(tableData);
}
CodePudding user response:
You don't calculate the loan amount until the end of the loop - after the first month is put into the table.
Move this line:
loan_amount = parseFloat(loan_amount - monthly_principal).toFixed(DIGIT_PRECISION);`
To just after the monthly_principal
declaration.