Compounding interest calculator in a loop in JavaScript - javascript

I am working on a calculator that calculates simple interest and compounding interest. All good, with the simple interest, but I can't seem to be able to solve the problem with the compounding interest, using a loop. I need a loop, because pushing the data into an array to use it in a chart later.
I have the formula from here: https://www.moneysmart.gov.au/managing-your-money/saving/compound-interest
I am using this as reference: https://www.bankrate.com/calculators/retirement/roi-calculator.aspx
The code is in work here: http://www.course0001.com/fiverr/iddqd
I have this so far(updated):
// Inputs from user:
// Initial deposit (starting balance)
// Number of years
// Interest
// Frequent Deposit amount
// Deposit and compound frequency (monthly, weekly, yearly)
// Calculations
var investedCapitalArray = [];
var simpleInterestArray = [];
var compoundInterestArray = [];
var compoundPrincipal = 0;
var years = [];
var accumulatedInvestment;
function calculate() {
years = [];
let interest = rateNumeric.getNumber() / 100; // annual interest rate
let additionalDeposit = additionalNumeric.getNumber(); // Regular deposit
let frequency = freqInput.value; // Frequency of regular deposit
let initialDeposit = initialNumeric.getNumber();
let taxRate = taxNumeric.getNumber();
// Invested captal amount first year
investedCapitalArray = [];
investedCapitalArray.push(initialDeposit + (frequency * additionalDeposit));
// simple interest first year
simpleInterestArray = [];
simpleInterestArray.push((investedCapitalArray[0] * ( (interest) / 100)) * (1 - taxRate));
// compund interest first year
compoundInterestArray = [];
let firstYearInvestment = investedCapitalArray[0]; // First deposit + regular deposits in first year
for (let i = 1 ; i < yearsInput.value ; i++) {
// Invested capital over the years (correct results)
investedCapitalArray.push( (investedCapitalArray[i-1]) +
(frequency * additionalDeposit) );
// simple interest over the years (correct results)
simpleInterestArray.push( simpleInterestArray[i-1] +
((firstYearInvestment +
((frequency) * additionalDeposit) * i ) * interest) );
// compound interest over the years (incorrect results)
compoundInterestArray.push( investedCapitalArray[i-1] *
Math.pow(1 + interest / 100, i) - initialDeposit);
years.push('Year' +i);
}
}

The issue is with the paranthesis you should use (investedCapitalArray[i - 1] + compoundInterestArray[i - 1]) * (1 + 0.07). Thanks

I think the problem is with unboxing the object. Try this:
compoundInterestArray.push( compoundInterestArray[i-1] + (parseInt(investedCapitalArray[i-1]) + parseInt(simpleInterestArray[i-1])) * ( rateNumberic.getNumber() / 100)) );

Thank you everyone for the inputs, after thoroughly researching the compounding interest topic, I wrote an algorithm that works perfectly. It's actually quite simple.
My algorithm is based on this explanation:
"What Is Compound Interest? Compound interest (or compounding interest) is interest calculated on the initial principal, which also includes all of the accumulated interest of previous periods of a deposit or loan."
Therefore it works like this in a loop:
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest));
Full code below.
for (let i = 1; i < yearsInput.value; i++) {
// Invested capital over the years (works fine)
investedCapital = (investedCapitalArray[i - 1]) +
(frequency * additionalDeposit);
investedCapitalArray.push(investedCapital);
// imple interest over the years (works fine)
simpleInterest = simpleInterestArray[i - 1] +
((firstYearInvestment + (frequency * additionalDeposit) * i) * interest);
simpleInterestArray.push(simpleInterest);
// compound interest over the years (correct results)
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest)));
compoundInterestArray.push(compoundInterest);
}

Related

Calculate multiple values ​in a loop

In a future income calculator, I need to display the data accumulated in 5 years, 10 years and 15 years.
In this account, I take the value of the monthly contributions, after 12 months, I apply the annual profitability, with that the final value of one year is concluded.
To get the value of the second year, I take the initial value of the sum of the 12 months and make the sum with the value of the 12 months with profitability.
The account is as follows ...
contributions = 536,06;
profitability = 4.27;
fixedYearVal = 536,06 * 12; // 6.432,72
profitabilityVal = (profitability / 100) * fixedYearVal;
fixedYearprofitability = fixedYearVal + profitabilityVal;
With that, I discover the first year with profitability.
The value for the second year will be (secondYear = fixedYearVal + fixedYearprofitability).
The final amount for the second year will be
percentSecondYear = (profitability / 100) * secondYear;
finalSecondYear = percentSecondYear + secondYear;
And the value of the third year is going to be
thirYear = finalSecondYear + fixedYearVal;
percentthirdYear = (profitability / 100) * thirYear;
finalThirdyear = percentthirdYear + thirYear;
Anyway, as I said, I need it for 5 years, 10 years and 15 years, and I can't imagine any other way than to make thousands of lines, I thought about doing it with a for in Javascript but with this data boo I found myself lost .
😢
I threw something together. Maybe this can help you get started. The idea is 1) set some base values 2) throw it through a loop of n years you want to calculate. 3) return the final results in an array so you can see a year by year
// Calculate the next year
const caclNextYear = (lastYear, fixedYearVal, profitability) => {
const nextYr = lastYear + fixedYearVal;
const percentSecondYear = (profitability / 100) * nextYr;
const finalYr = percentSecondYear + nextYr;
return finalYr;
};
// Calc years by number of years
const estimateByYears = (years) => {
const contributions = 536.06;
const profitability = 4.27;
const fixedYearVal = 536.06 * 12; // 6.432,72
const profitabilityVal = (profitability / 100) * fixedYearVal;
const fixedYearprofitability = fixedYearVal + profitabilityVal;
const yearByYear = [fixedYearprofitability];
for (let i = 1; i < years; i++) {
let lastYr = yearByYear[yearByYear.length - 1];
yearByYear.push(caclNextYear(lastYr, fixedYearVal, profitability));
}
return yearByYear;
};
// Call
const yearByYear = estimateByYears(5);
// yearByYear : [6707.397144, 13701.200146048799, 20993.63853628508, 28597.46404578445, 36525.97290453945
console.log('yearByYear', yearByYear);

Compounding interest monthly with a deposit

I want to compound interest on a weekly/fortnightly/monthly/annual basis.
I also want an option to have a deposit amount that can be added in.
I have already tried the standard formula of calculating the final amount accrued, as seen here:
(source: gstatic.com)
For example here is my method for calculating the interest compounding weekly:
function calculateWeekly(state: any) {
const { savings, deposit ,interest, timePeriodSelector, timePeriodLength } = state;
let numberOfYears = 0;
if (timePeriodSelector === "weekly") {
numberOfYears = timePeriodLength / weeksInAYear;
} else if (timePeriodSelector === "fortnightly") {
numberOfYears = (timePeriodLength / weeksInAYear) * 2;
} else if (timePeriodSelector === "monthly") {
numberOfYears = (timePeriodLength / weeksInAYear) * weeksInAMonth;
} else if (timePeriodSelector === "annually") {
numberOfYears = (timePeriodLength / weeksInAYear) * weeksInAYear;
}
const weeklyRate = interest / 100 / weeksInAYear;
const lengthOfCompunding = numberOfYears * weeksInAYear;
let startingFigure = parseInt(savings) + parseInt(deposit);
//total gets added on for every time cycle of week
let total =
(startingFigure * (Math.pow(1 + weeklyRate, lengthOfCompunding) - 1)) / weeklyRate;
return roundToTwoDP(total);
}
The issue with the above code is that the deposit gets added into the calculation every time the interest accrues. So a deposit of $10 weekly for 10 weeks will actually get added up to $100.
I attempted a method to accrue the interest using a loop for each week here:
// loops how many times to compound the interest
for(let i = numberOfYears - (1/weeksInAYear); i > 0; i-= (1/weeksInAYear)){
let interestGained = (total * (Math.pow((1 + weeklyRate), lengthOfCompunding))) - total;
total += interestGained + savings;
}
Thanks for any help!
This should do what you want:
const range = (min, max) => {
const size = 1 + max - min
return [...Array(size).keys()].map(n => n + min)
}
const weeksInAYear = 52
const addWeeklyInterest = interestRatePerWeek => (savings, _) => savings + savings * interestRatePerWeek
const calculateTotal = (savings, numberOfYears, interestRatePerWeek) => {
const numberOfWeeks = numberOfYears * weeksInAYear
return range(1, numberOfWeeks).reduce(addWeeklyInterest(interestRatePerWeek), savings)
}
console.log(calculateTotal(1000.00, 1, 0.02))
Output is 2800.328185448178. You might want to round that for display purposes, but also keep in mind that if accuracy is important, you can't use floating-point numbers.

Calculate Net Present Value

I am get a formula to calculate the Net Present Value using Rent, Number of periods, Discount Rate and Future Value.I am able to get the Present Value however, I need a formula to calculate the Net Present Value on today's date or any date a user inputs. My code is as below:
function PV() {
var future = 5000;
var type = 1;
periods = 12;
rate = document.getElementById("rate").value;
var ratePercent = periods * 100;
rate = Math.pow(1 + rate / 100, 1 / 365) - 1;
rate = eval(rate);
periods = eval(periods);
// Return present value
if (rate === 0) {
document.getElementById("presentResultValue").value = -payment * periods - future;
} else {
document.getElementById("presentResultValue").value = (
(((1 - Math.pow(1 + rate, periods)) / rate) * payment * (1 + rate * type) - future) /
Math.pow(1 + rate, periods)
).toFixed(2);
}
}
I am also using Excel to calculate this but need a way to convert it to Javascript. I am also attaching my work with excel. ExcelNPV I am still learning JavaScript so any help will be greatly appreciated. Thank you.
Came across NPV formula on my project and had to create a function for it. Finance.js is great but I didn't want to clutter my code with it because my problem was just getting this formula.
ES5 Function
/**
* Calculates the Net Present Value of a given initial investment
* cost and an array of cash flow values with the specified discount rate.
*
* #param {number} rate - The discount rate percentage
* #param {number} initialCost - The initial investment
* #param {array} cashFlows - An array of future payment amounts
* #return {number} The calculated Net Present Value
*/
function getNPV(rate, initialCost, cashFlows) {
var npv = initialCost;
for (var i = 0; i < cashFlows.length; i++) {
npv += cashFlows[i] / Math.pow(rate / 100 + 1, i + 1);
}
return npv;
}
Using the function:
var rate = 10;
var initialCost = -25000;
var cashFlows = [-10000, 0, 10000, 30000, 100000];
console.log(getNPV(rate, initialCost, cashFlows));
// expected output: 56004.77488497429
JavaScript ES6 Function:
https://www.evermade.fi/net-present-value-npv-formula-for-javascript/
/**
* Calculates the Net Present Value of a given initial investment
* cost and an array of cash flow values with the specified discount rate.
* #param {number} rate - The discount rate percentage
* #param {number} initialCost - The initial investment
* #param {array} cashFlows - An array of future payment amounts
* #return {number} The calculated Net Present Value
*/
function getNPV(rate, initialCost, cashFlows) {
return cashFlows.reduce(
(accumulator, currentValue, index) =>
accumulator + currentValue / Math.pow(rate / 100 + 1, index + 1),
initialCost
);
}
I've explained most of it on my blogpost.
Hope this helps :)
One big thing you are missing with this is the cost.
You have periods, you have rate, you have rate percent. But there is nothing there for the "cost".
You say you have this in Excel, and other languages. If you understand the calculations in Excel, then you may understand how you should do it in JavaScript.
In Excel you use the nifty function =NPV(.... where it takes 2 arguments. The first is the "RATE" and the second is the "VALUE" which can be multiple values. When you do this in Excel, one of the values you pass in would be the total cost. So you have something like this....
=NPV(2%,[total cost],[Year1Value],[Year2Value],[Year3Value],....) or =NPV(A1,A2:A12)
The "Total Cost" would go where you spend the money....assuming its at the end of Year 1, it would go before the "value" / return from year one.
With that being said, another thing to consider is determining WHEN the cost was needed.
If the cost is upfront, then it would be taken out of the "array" of values section and added to the NPV calculations such as....
=NPV(A1,A3:A12) + A2
Where cell A2 is the Cost (upfront) and A1 is the rate and A3-A12 are all the returns.
As a simple example, if you have the rate somewhere on the page, you can loop through the arguments that are going to be passed to it such as below....
function NPV() {
var args = [];
for (i = 0; i < arguments.length; i++) {
args = args.concat(arguments[i]);
}
var rate = document.getElementById("rate").value;
var value = 0;
// loop through each argument, and calculate the value
// based on the rate, and add it to the "value" variable
// creating a running total
for (var i = 1; i < args.length; i++) {
value = value + ((args[i])/(Math.pow(1 + rate, i)));
}
return value;
}
Additionally, you could also look for a library such as Finanace.JS http://financejs.org/
This worked for me
function getNPV(rate, a, payment) {
var npv = 0;
for (var i = 0; i < a.length; i++) {
npv += payment / Math.pow(1 + rate, a[i]);
console.log(payment / Math.pow(1 + rate, a[i]))
}
return npv;
}

How to calculate interest javascript

I'm trying to create a function that returns the money I have after x years of interest.
var calculateInterest = function(total, year, rate) {
(var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4))
}
console.log(calculateInterest(915, 13, 2));
I'm not getting it to work and I'm stuck!
Any advice?
You were close. You don't need parentheses around var interest:
var calculateInterest = function(total, year, rate) {
var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4));
}
var answer = calculateInterest(915, 13, 2);
console.log(answer);
I'd recommend cleaning it up a little to:
var calculateInterest = function(total, years, ratePercent, roundToPlaces) {
var interestRate = ((ratePercent / 100) + 1);
return (total * Math.pow(interestRate, years)).toFixed(roundToPlaces);
}
var answer = calculateInterest(915, 13, 2, 2);
console.log(answer);
You don't need parseFloat() if the variable is already a number (it's needed when you're parsing from a string, which is not the case here). I am adding a parameter to specify how many decimal places to round to is useful so you can control the output of the function.
Updated fiddle

Insert calculated values into different DOM elements

I have a working formula that calculates PMT based on the interest rates, I see that it's working because the output in the console.log is correct. My question is, how can I take the results in the console.log and place each amount into it's own div?
For example, the first div is 4.125%, I want to display the dollar amount in the div right after it, then for the 3.125%, I want to display the dollar amount right after it and so on
Here is what I have http://jsfiddle.net/yecDj/19/
var p = 1000;
var thirtyYear = parseFloat(-Math.abs(360)); /*30 YR term in months*/
for (var i = 1; i < 5; i++) {
var costPerThousand = "$" + (p * ((parseFloat(document.getElementById('rate' + i).innerHTML) / 100 / 12) / (1 - (Math.pow((1 + (parseFloat(document.getElementById('rate' + i).innerHTML) / 100 / 12)), thirtyYear))))).toFixed(2);
console.log(costPerThousand);
}
I'm looking to do this in javascript only
Replace your console.log with:
document.querySelector('#rate' + i).textContent = costPerThousand;
querySelector
textContent
Fiddle

Categories