Reputation: 19
Have a basic javascript interest calculator, that I need to modify.
Now it calculate only first deposit, trying to add regular (every year) deposit. But have no idea how to do it correct :(
The basic code is working fine: https://jsfiddle.net/zpv24m1e/6/
function calc() {
var princ = 1000; // start deposit
var add = 500; // yearly deposit (need plus it every year)
var rate = 0.0225;
var years = 10;
var power = Math.pow((1 + rate), years);
var summ = Math.round(princ * power * 100) / 100;
var profit = Math.round((summ - princ) * 100) / 100;
$("#demo").html("Total: "+summ+" Profit: "+profit);
}
Upvotes: 1
Views: 1803
Reputation: 7706
You can calculated it in the following way:
function calc() {
var princ = 1000; // start deposit
var totalDeposit = princ;
var add = 500; // yearly deposit (need plus it every year)
var rate = 0.0225;
var years = 10;
for(var i=0;i<years;i++)
{
if(i!=0)
{
princ += 500;
totalDeposit +=500;
}
princ += princ * rate;
}
$("#demo").html("Total: "+princ.toFixed(2)+" Profit: "+(princ-totalDeposit).toFixed(2));
}
This is the case when you add regular every year except the first year.
Upvotes: 2