>鑑於利率,本金金額和每月付款,本JavaScript代碼計算貸款還款詳細信息,包括支付的總利息和還款期限。 最初的示例使用硬編碼值;改進的版本將計算封裝在可重複使用的函數中。
>>初始代碼(帶有硬編碼值):
<code class="language-javascript">// FORMULA: p = x*(1 - (1+r)^-n)/r (where p is the principal, x is the monthly payment, r is the monthly interest rate, and n is the number of payments) var interest = 15; // Annual interest rate var rate = interest / 100; // Monthly interest rate var principal = 1000; // Loan amount var payment = 100; // Monthly payment var noofpay = 12; // Number of payments (months) var nper1 = Math.log(1 - ((principal / payment) * (rate / noofpay))); var nper2 = Math.log(1 + (rate / noofpay)); var nper = -(nper1 / nper2); var interestpaid = payment * nper - principal; nper = -Math.round(nper); var nyear = Math.floor(nper / 12); var nmonth = nper % 12; var period; if (nper > 0) { period = nyear + " Year(s)" + (nmonth > 0 ? " and " + nmonth + " Month(s)" : ""); } else { period = "Invalid Values"; interestpaid = 0; } console.log("Monthly Payments: " + period + ", Total Interest Paid: " + interestpaid.toFixed(2));</code>
改進的代碼(作為函數):
<code class="language-javascript">// Loan Calculator Function function calculateLoan(interest, principal, payment) { var rate = interest / 100; // Annual interest rate to monthly var noofpay = 12; // Assuming monthly payments var nper1 = Math.log(1 - ((principal / payment) * (rate / noofpay))); var nper2 = Math.log(1 + (rate / noofpay)); if (isNaN(nper1) || isNaN(nper2)) { // Handle invalid input that would cause NaN return { period: "Invalid Values", interestpaid: 0 }; } var nper = -(nper1 / nper2); var interestpaid = payment * nper - principal; nper = -Math.round(nper); var nyear = Math.floor(nper / 12); var nmonth = nper % 12; var period = nper > 0 ? nyear + " Year(s)" + (nmonth > 0 ? " and " + nmonth + " Month(s)" : "") : "Invalid Values"; return { period: period, interestpaid: interestpaid.toFixed(2) }; } // Example usage: var results = calculateLoan(15, 1000, 100); console.log("Monthly Payments: " + results.period + ", Total Interest Paid: $" + results.interestpaid);</code>>由無效輸入產生),並返回包含計算值的對象,從而使其更強大,更易於集成到較大的應用程序中。 請記住,該計算假定每月付款。 對於其他付款頻率,
>變量和利率計算需要調整。 >
這些常見問題解答是簡潔地回答的,以適合提供的代碼,並避免不必要的重複。 更詳細的解釋將適合一個單獨的,更全面的文檔。
>如何實現:NaN
noofpay
常見問題(常見問題解答) - 簡潔答案:>
calculateLoan
calculateLoan
isNaN()
>calculateLoan
總付款:NaN
這只是
以上是JavaScript利息貸款計算器算法的詳細內容。更多資訊請關注PHP中文網其他相關文章!