In this article, We will show you the programs to calculate compound interest in javascript. At last, we’ll also make a browser-based calculator for the compound interest. So let’s get started.
Compound interest is a concept in finance that states that interest can be added to the principal sum invested so that the total amount grows at a faster rate than simple interest. It is actually interest on the interest that accumulates and grows exponentially over time.
Total Amount: A = P(1 + R/100)^T
Compound Interest: CI = A – P
Where P: principle amount, T: time, and R: Interest rate
For example, if you borrow $20000 for three years at an annual compounded interest rate of 6%, you will pay the interest of $3,820.32 and $23,820.32 in the total.
Let’s create a program to calculate compound interest in javascript.
// Function to calculate compound interest in javascript
function compoundInterest(p, r, t) {
const total = p * Math.pow((1 + r / 100), t);
const interest = total - p;
return {
total: parseFloat(total.toFixed(2)),
interest: parseFloat(interest.toFixed(2))
}
}
console.log(compoundInterest(10000, 10, 3))
{total: 13310, interest: 3310}
Now it’s time to create the browser-based compound interest calculator with the three input number fields (Principle, Rate of interest, Time in Years) and a button. The total compounded amount and interest will be shown on the screen with a button click. Here is the code for that.
<html>
<head>
</head>
<body>
<input type="number" placeholder="Principle amount" id="p">
<input type="number" placeholder="Rate of interest" id="r">
<input type="number" placeholder="Time" id="t">
<button id="c">Calculate Compount Interst</button>
<p id="d"></p>
<script>
function compoundInterest(p, r, t) {
const total = p * Math.pow((1 + r / 100), t);
const interest = total - p;
return {
total: parseFloat(total.toFixed(2)),
interest: parseFloat(interest.toFixed(2))
}
}
function render() {
const t = document.querySelector("#t").value;
const p = document.querySelector("#p").value;
const r = document.querySelector("#r").value;
const v = compoundInterest(p, r, t);
const result = `Interest: $${v.interest}, Total Amt: $${v.total}`;
document.querySelector("#d").innerHTML = result
}
document.querySelector("#c").addEventListener("click", render);
</script>
</body>
</html>