我正在嘗試製作一個javascript貸款計算器程序。我似乎無法讓我的循環在每一行上輸入不同的數字。假設顯示24個月,36個月,48個月和60個月開始支付的金額。我正在使用函數來進行計算,但我總是得到24個月的結果。我知道你必須將nummonths改爲36,48和60,但我不知道這樣做。我認爲循環會在每次循環時增加12個月。另外你會如何將數字格式化爲貨幣?最後我得到一個非常長的數字。我試着在calculate()上做parseFloat,但是我得到一個錯誤。 這裏是我的代碼:Javascript循環程序
<html>
<BODY BGCOLOR="#FFC0CB">
<head>
<title>Chapter 6 Assignment 2</title>
</head>
<body>
<h1>Loan Calculator</h1>
<script type="text/javascript">
var vehicleprice = window.prompt("What is the vehicle price?", "");
var downpayment = window.prompt("What is the amount of the down payment?", "");
var annualinterest = window.prompt("What is the annual interest rate for the loan?", "");
var nummonths = 24
var loanamount = vehicleprice - downpayment
var monthlyinterest = annualinterest/1200
vehicleprice = parseFloat(vehicleprice).toFixed(2);
downpayment = parseFloat(downpayment).toFixed(2);
loanamount = parseFloat(loanamount).toFixed(2);
function calculate()
{
var baseamount = Math.pow(1 + monthlyinterest, nummonths);
return loanamount * monthlyinterest/(1 - (1/baseamount));
}
document.write("Vehicle price: $" +vehicleprice+ "<br>");
document.write("Down payment: $" +downpayment+ "<br>");
document.write("Interest Rate: " +annualinterest+ "%<br>");
document.write("Loan Amount: $" +loanamount+ "<br>");
for (var count=2;count<=6;count+=1)
{
document.write(+calculate()+"<br />");
}
</script>
</body>
</html>
謝謝!你如何將結果格式化爲貨幣? – jaramore
我無法使accounting.js正常工作。你怎麼做呢? – jaramore
看看這裏格式化http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript – Stuart