Ale*_*erg 4 javascript finance
我正在尝试编写一个脚本,用户在该脚本中插入月收入,并在30年后获得复合利息的未来值.就像现在一样,我已经为测试目的分配了一些值.
// Future Value
var investment = 800;
var annualRate = 2;
var monthlyRate = annualRate / 12 / 100;
var years = 30;
var months = years * 12;
var futureValue = 0;
for ( i = 1; i <= months; i++ ) {
futureValue = futureValue + investment * Math.pow(1 + monthlyRate, months);
}
Run Code Online (Sandbox Code Playgroud)
问题是,我实际上是从使用内置FV()公式的Excel电子表格中构建这个,并且在交叉检查时,我的结果完全关闭...任何想法我做错了因为我不进金融数学.提前致谢.
这Math.pow是不必要的,因为您futureValue逐月计算和递增.简单地乘以1 + monthlyRate.您还希望在乘以之前将投资的当前值添加到新投资:
for ( i = 1; i <= months; i++ ) {
futureValue = (futureValue + investment) * (1 + monthlyRate);
}
Run Code Online (Sandbox Code Playgroud)
或者,您也可以使用以下公式一次性计算:
futureValue = investment * (Math.pow(1 + monthlyRate, months) - 1) / monthlyRate;
Run Code Online (Sandbox Code Playgroud)
小智 6
下面是计算复利的代码。
function calculate() {
p = document.getElementById("p").value;
n = document.getElementById("n").value; // no. of compoundings per year
t = document.getElementById("t").value; // no. of years
r = document.getElementById("r").value;
result = document.getElementById("result");
// The equation is A = p * [[1 + (r/n)] ^ nt]
A = (p * Math.pow((1 + (r / (n * 100))), (n * t)));
// toFixed is used for rounding the amount with two decimal places.
result.innerHTML = "The total amount is " + A.toFixed(2);
result.innerHTML += "<br> The interest is " + (A.toFixed(2) - p).toFixed(2);
}Run Code Online (Sandbox Code Playgroud)
div {
display: table-row;
}
label,
input {
display: table-cell;
}Run Code Online (Sandbox Code Playgroud)
<html>
<head>
<title>Compound Interest Calculation using jQuery</title>
</head>
<body>
<h1>Compound Interest Calculation Using jQuery</h1>
<div> <label>Amount: </label> <input id="p"> </div>
<div> <label>Rate (%): </label> <input id="r"> </div>
<div> <label>No. of Years: </label> <input id="t"> </div>
<div> <label>Compunding Times Per Year: </label> <input id="n" value="1"> </div>
<button onclick="calculate()">Calculate</button>
<p id="result"></p>
</body>
</html>Run Code Online (Sandbox Code Playgroud)