JSFiddle - React, Tailwind, and code Playground
JavaScript
// Example usage:
const balanceBeforeChange = 10000;
const balanceAfterChange = 11000;
const changeDate = 17; // 17th June
const annualInterestRate = 4; // 4%
const daysInMonth = 30; // Number of days in June
const interestC = calculateMonthlyCompoundInterest(balanceBeforeChange, balanceAfterChange, changeDate, annualInterestRate, daysInMonth);
const interestS = calculateMonthlySimpleInterest(balanceBeforeChange, balanceAfterChange, changeDate, annualInterestRate, daysInMonth);
const text = `The total compound interest for June is: €${interestC}\n\nThe total simple interest for June is: €${interestS}`;
console.log(text);
alert(text);
function calculateMonthlyCompoundInterest(balanceBeforeChange, balanceAfterChange, changeDate, annualInterestRate, daysInMonth) {
// Convert annual interest rate to a decimal
const annualRateDecimal = annualInterestRate / 100;
// Calculate monthly interest rate for compound interest
const monthlyRate = Math.pow((1 + annualRateDecimal), 1 / 12) - 1;
// Calculate daily interest rate (for compound calculations, we use the monthly rate for whole days)
const dailyRate = monthlyRate / daysInMonth;
// Calculate the number of days before and after the change
const daysBeforeChange = changeDate - 1; // Change happens on 'changeDate', so days before it are 'changeDate - 1'
const daysAfterChange = daysInMonth - changeDate + 1;
// Calculate interest for each period using compound interest formula
const interestBeforeChange = balanceBeforeChange * Math.pow(1 + dailyRate, daysBeforeChange) - balanceBeforeChange;
const interestAfterChange = balanceAfterChange * Math.pow(1 + dailyRate, daysAfterChange) - balanceAfterChange;
// Sum the interests for the total interest
const totalInterest = interestBeforeChange + interestAfterChange;
return totalInterest.toFixed(4);
}
function calculateMonthlySimpleInterest(balanceBeforeChange, balanceAfterChange, changeDate, annualInterestRate,...