我试图显示支付的总利息的值,一旦该值达到零。因此,基本上每个月的所有利息都作为最终价值加在一起。然后,我需要以百分比显示每月利息的价值。我不能弄清楚这个公式。这是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;


}

最佳答案

循环总结您的兴趣。确保该变量在while循环之外,否则它将超出范围。

var sumInterest = 0;
while ( amount > 0 ) {
    var interest = amount * rate;
    sumInterest += interest;
    var principal = monthly - interest;
    //rest of code here

09-30 22:42