Compound Interest Calculator
by devtails
HTML
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<label for="start">Start</label>
<input id="start" name="start" type="date"/>
<label for="end">Date</label>
<input id="end" name="end" type="date"/>
<label for="principal">Principal</label>
<input id="principal" name="principal" type="number" value="0"/>
<label for="monthly">Monthly Deposit</label>
<input id="monthly" name="monthly" type="number" value="500"/>
<label for="interest">Annual Interest Rate (%)</label>
<input id="interest" name="interest" type="number" value="5"/>
<label for="view">View</label>
<select id="view" name="view">
<option value="month">Month</option>
<option value="year" selected>Year</option>
</select>
<button id="submit">Submit</button>
<div id="container" style="width:100%; height:800px;"></div>
JavaScript
function calulate() {
const startInput = document.getElementById("start");
const endInput = document.getElementById("end");
const principalInput = document.getElementById("principal");
const interestInput = document.getElementById("interest");
const monthlyInput = document.getElementById("monthly");
const viewInput = document.getElementById("view");
let isMonthly = viewInput.value === "month";
let startMoment = new moment(startInput.value);
let endMoment = new moment(endInput.value);
let principal = Number(principalInput.value);
let monthlyDeposit = Number(monthlyInput.value);
let periodMonths = endMoment.diff(startMoment, "month") + 1;
let annualInterestRate = Number(interestInput.value) / 100;
let compoundedData = [principal];
let interestData = [0];
let principalData = [principal];
for (let i = 1; i < periodMonths; i++) {
let lastAmount = compoundedData[i - 1];
let newTotalBeforeInterest = lastAmount + monthlyDeposit;
let newTotalAfterInterest = Math.round(newTotalBeforeInterest * (1 + annualInterestRate / 12));
let interest = newTotalAfterInterest - newTotalBeforeInterest;
principalData.push(principalData[i - 1] + monthlyDeposit);
interestData.push(interestData[i - 1] + interest);
compoundedData.push(newTotalAfterInterest);
}
let finalCompoundedData = [];
let finalInterestData = [];
let finalPrincipalData = [];
let numPeriodsPerPoint = isMonthly ? 1 : 12
for (let i = 0; i < periodMonths; i += numPeriodsPerPoint) {
finalCompoundedData.push({
y: compoundedData[i]
});
finalInterestData.push({
y: interestData[i]
});
finalPrincipalData.push({
y: principalData[i]
});
}
var myChart = Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Compound Interest'
},
xAxis: {
title: {
text: 'Month'
},
labels: {
formatter() {
let unit = isMonthly ?...