# Investment formula. How to fix to calculate correctly?

Hello guys,

I am learning JS - left lot what to learn…

Now I try to make calculator, witch calculate the result, witch I get after some years and show linear in chart (chart works).

In a forms I enter amount of money, witch I will pay periodically, choose periods (annually, quarterly, two times a year, monthly).
Then I enter the number of years for how long I want to invest.
And finally I enter rates.

Lets say:

I invest for two years, invest 100 Eur monthly with 8% rates.

So after 1 year I invested 1200 Eur. and should have 1296 Eur.

After 2nd years I should have 2695.68 Eur. (1296 (from 1st year) + 1200 (invested monthly) + rates).

I try to find what I wrote wrong in a code (and formula), that its calculating bad results (and chart appears bad - by bad results of calculating).

Could you please check my function code:

``````function calculateGrowth(e) {
e.preventDefault();
data.length = 0;
labels.length = 0;
let growth = 0;
try {
const amount = parseInt(Amount.value);
const period = parseInt(years.value);
const interest = parseInt(rates.value);
const comp = parseInt(compound.value);

for(let i = 1; i <= period; i++) {
const final = (amount * comp / 100 * interest, comp * i);
data.push(toDecimal(final, 2));
labels.push("Year " + i);
growth = toDecimal(final, 2);
}
//
message.innerText = `You will get \${growth} Eur. after \${period} years`;
drawGraph();
} catch (error) {
console.error(error);
}
}
``````

I think the problem is in my formula…

Or you know easier way to calculate thing what I want and you recommend me to change my function somehow?!

P.S. I was googling, tried another formulas with no right result.

Which library are you using for the toDecimal function?

There are a lot of moving parts to that code, and many assumptions that can be wrongly made about how you intend for things to work.

Can you please put together a demo version of the poorly calculated code so that we can see it running in action, and provide enough initial input for us to accurately experience the problem?

You will not have invested €1200 throughout all of the first 12 months so the interest will not be €96.

Assuming interest is calculated for each month but only added to capital annually, the interest for the first 12 months will be €52.

Sorry… here is full code:

``````const context = document.getElementById("data-set").getContext("2d");
let line = new Chart(context, {});
//Values from the form
const amount = document.getElementById("amount");
const years = document.getElementById("years");
const rates = document.getElementById("rates");
const compound = document.getElementById("compound");

//Messge
const message = document.getElementById("message");

//The calculate button
const button = document.querySelector(".input-group button");
//Attach an event listener

const data = [];
const labels = [];

function calculateGrowth(e) {
e.preventDefault();
data.length = 0;
labels.length = 0;
let growth = 0;
try {
const initial = parseInt(amount.value);
const period = parseInt(years.value);
const interest = parseInt(rates.value);
const comp = parseInt(compound.value);

for(let i = 1; i <= period; i++) {
const final = (initial * comp / 100 * interest, comp * i);
data.push(toDecimal(final, 2));
labels.push("Year " + i);
growth = toDecimal(final, 2);
}
//
message.innerText = `Get \${growth} eur after \${period} years`;
drawGraph();
} catch (error) {
console.error(error);
}
}

function drawGraph() {
line.destroy();
line = new Chart(context, {
type: 'line',
data: {
labels,
datasets: [{
label: "Prieaugis",
data,
fill: true,
backgroundColor: "rgba(12, 141, 0, 0.7)",
borderWidth: 3
}]
}
});
}

function toDecimal(value, decimals) {
return +value.toFixed(decimals);
}
``````

Thank you for your minds Why not? :o If I invest 100 each month, it should be 1200 at the end of the year, and if the interest rate is 8%, 1200 should increase by 96 (1200 + 96 = 1296).

If you invested €1200 at the start of the year and made no monthly payments you would expect €96 interest.

If you’re trying to make this an accurate representation of interest, for example from a savings account, you should use the formula for Compound Interest. It is nothing like what you’ve coded. You could Google “compound interest formula” it and get the details.

You haven’t invested 1,200 for 12 months. You’ve invested 100 for 12 months, 200 for 11 months, … 1,200 for 1 month.

1 Like

Start of Month 1: Invest 100.00
Start of Month 2: 100.00*1.08 = 108.00 + Invest 100.00, total 208.00
Start of Month 3: 208*1.08 = 224.64 + Invest 100.00, total 324.64
Start of Month 4, 324.64*1.08 = 350.6112 + Invest 100, total 450.6112
Start of Month 5: 450.6112*1.08 = 486.660096 + Invest 100, total 586.660096

Is that an accurate representation of the values that you want your code to achieve?

The 8% interest rate would be per year, not per month.

Savings acccounts usually add interest to capital on the anniversary of opening the account, not each month. Interest does not earn interest until it is added to capital.

I calculate the balance at the end of the first year would be €1252 (just before the 13th payment into the account) and at the end of the second year would be €2604.16.

With paying into the account every month, the usual compound interest formula would not apply.

Thanks Paul_Wilkins,

No, I want calculate rates after 12 months (cause I can choose frequency (how often I want to pay) - yearly, monthly, two times a year).

I found formula in google, tried it in console - it fits for me perfectly: x = (p + x) * (1 + r / 100);

All code is:

``````console.clear();

(function calc() {
//frequency is how often you pay - monthly, yearly, etc.
let frequency = 12;
//sum is sum of regular payment
let sumP = 100;
// p is principal amount
let p = frequency * sumP;
// t is time
let t = 2;
// r is interest rate
let r = 8;
// x is the final interest
let x = p;
for (let i = 1; i < t; i++) {
if (i == 1) {
x *= 1 + r / 100;
}
x = (p + x) * (1 + r / 100);
}
console.log(x.toFixed(2));
})();

``````

I try to find a problem here (tried to adapt formula I found and tried) but function calculate sth wrong ``````function calculateGrowth(e) {
e.preventDefault();
data.length = 0;
labels.length = 0;
let growth = 0;
try {
const initial = parseInt(amount.value);
const period = parseInt(years.value);
const interest = parseInt(rates.value);
const comp = parseInt(compound.value);

for(let i = 1; i < period; i++) {
//x = (p + x) * (1 + r / 100);
const final = (comp * initial + comp * initial) * (1 + interest / 100);
data.push(toDecimal(final, 2));
labels.push("Year " + i);
growth = toDecimal(final, 2);
}
//
message.innerText = `Get \${growth} eur after \${period} years`;
drawGraph();
} catch (error) {
console.error(error);
}
}
``````

function is ~ simple, but do not see where is the problem… %o

You can turn that working function in to one that takes function parameters, and just use that from your code.

``````// for example, to calculate 12-monthly payments of \$100 for 2 years at 8%
// call it as follows: const total = calculateInvestment(12, 100, 2, 8)
function calculateInvestment(frequency, payment, time, interestRate) {
let principal = frequency * payment;
let total = principal;
for (let i = 1; i < time; i++) {
if (i == 1) {
total *= 1 + interestRate / 100;
}
total = (total + principal) * (1 + interestRate / 100);
}
}
``````

Your code can then call that calculateInvestment function to properly calculate the amount, and then show it as a graph.

That calculateInvestment function can also be simplified to the following:

``````// for example, to calculate 12-monthly payments of \$100 for 2 years at 8%
// call it as follows: const total = calculateInvestment(12, 100, 2, 8);
function calculateInvestment(frequency, payment, time, interestRate) {
const principal = frequency * payment;
let total = 0;
while (time--) {
total += principal;
total *= 1 + interestRate / 100;
}
}
``````

Or, using an object for the parameters, so that the parameters are easier to understand when calling the function:

``````// for example, to calculate 12-monthly payments of \$100 for 2 years at 8%
// call it as follows:
// const total = calculateInvestment({
//     frequency: 12,
//     payment: 100,
//     time: 2,
//     interestRate: 8
// });
function calculateInvestment({frequency, payment, time, interestRate}) {
const principal = frequency * payment;
let total = 0;
while (time--) {
total += principal;
total *= 1 + interestRate / 100;
}