Reputation: 43
Im trying to display the value of the total interest paid once the value hits zero. So basically all interest per month added together as a final value. Then I need to display the value of monthly interest in percent. I cannot figure out the formula for this. Here is the example of how it should look http://snag.gy/9vzGi.jpg
function buildResults() {
var amount = parseFloat(document.getElementById("loanAmt").value );
var monthly = parseInt(document.getElementById("monthlyPay").value );
var rate = parseFloat(document.getElementById("intRte").value );
rate = rate / 100 / 12;
var msg = "<table id='tablefont' border='3' width='65%'>";
msg += "<tr>";
msg += "<td>Month</td>";
msg += "<td>Principal Paid</td>";
msg += "<td>Interest Paid</td>";
msg += "<td>Loan Balance</td>";
msg += "</tr>";
newPrincipal=amount;
var m = 1; //months
while ( amount > 0 ) {
var interest = amount * rate;
var principal = monthly - interest;
if (principal > amount) {
principal = amount;
amount = 0.0;
} else {
amount -= principal;
}
var sum = (interest.toFixed(2) + m);
msg += "<tr><td align='left' bgcolor='pink'>"+m+"</td> \
<td align='left' bgcolor='pink'>$"+fixVal(principal,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>$"+fixVal(interest,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>$"+fixVal(amount,0,2,' ')+"</td></tr>";
m++;
}
var msg2 = "";
msg2 += "Loan Amount: $" + document.getElementById("loanAmt").value + "<br>";
msg2 += "Annual Interest: " + document.getElementById("intRte").value + "%" +"<br>";
msg2 += "Monthly Payment: $" + document.getElementById("monthlyPay").value + "<br>";
msg2 += "Monthly Interest: " + fixVal(interest,0,2,' ') +"<br>";
msg2 += "Months to pay off loan: " + (m-1) +"<br>";
msg2 += "Total Interest Paid: $" + sum + "<br>";
msg += "</table>";
document.getElementById("results").innerHTML = msg;
document.getElementById("overview").innerHTML = msg2;
}
Upvotes: 1
Views: 432
Reputation: 550
Sum your interests in a loop. Make sure the variable is outside the while loop, or it will go out of scope.
var sumInterest = 0;
while ( amount > 0 ) {
var interest = amount * rate;
sumInterest += interest;
var principal = monthly - interest;
//rest of code here
Upvotes: 2