ホームページ >ウェブフロントエンド >jsチュートリアル >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>
よくある質問(FAQ) - 簡潔な回答:NaN
noofpay
の実装方法:
上記の関数を使用します。 ユーザー入力用のHTMLフォームを作成し、JavaScriptを使用して関数を呼び出し、結果を表示します。 複利:calculateLoan
calculateLoan
isNaN()
総支払い:calculateLoan
毎月の支払い、融資期間、金利:NaN
このコードは、毎月の支払いを考慮して、ローン期間と総利息を計算します。 他のパラメーターを考慮して毎月の支払いまたは金利を計算するには、より複雑な数学的操作を伴う異なる形式のローン式を解く必要があります。
以上がJavaScript利息ローン計算機アルゴリズムの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。