I have to calculate compound profit.
for example, I have $100, increasing 10% monthly, and I have to calculate the total profit for 12 months. And I need a profit of every month in an array.
I have tried this
let capital = 100;
let month = 12;
let profit_percentage = 10;
let total_profit;
for (i = 0; i <= month; i++) {
total_profit = capital + (profit_percentage / 100) * 100;
console.log(total_profit);
}
There seems to be a bit of missing info here, but if "profit" means the amount greater than the previous month:
Profit month over month:
const m = ((P, p) =>
new Array(12).fill()
.reduce((a, v) => (a.push(a.at(-1) * (1 + p)), a), [P])
.map((v, i, a) => Math.round((a[i + 1] - v) * 100) / 100)
.slice(0, -1)
)(100, .1);
Then, total profit:
Math.round((m.reduce((a, v) => ((a += v), a), 0) * 100)) / 100
Take it:
const calculate = (capital, countMonth, profitPercentage) => {
const calc = (capital / 100) * profitPercentage;
if (countMonth === 1) return capital + calc;
return calculate(capital + calc, countMonth - 1, profitPercentage);
};
If you need array:
const calculate = (capital, countMonth, profitPercentage) => {
const calc = (capital / 100) * profitPercentage;
if (countMonth === 1) return calc;
return (
`${calc}, ` + calculate(capital + calc, countMonth - 1, profitPercentage)
);
};
console.log(calculate(capital, month, profit_percentage).split(", "));
The compound interest calculation can be done like this:
const capital = 100, month = 12; profit_percentage = 10,
factor=1+profit_percentage/100;
let total=capital;
for (let i = 1; i <= month; i++) {
total *= factor;
console.log(i,(total-capital).toFixed(2));
}
console.log("The resulting total after 12 months is "+total.toFixed(2))