In this tutorial, I will show you the program for how to calculate simple interest in javascript.
Simple interest is the interest on a loan that is calculated and charged only on the principal balance of the loan. It is calculated by multiplying the principle amount, rate of interest, and a number of years and dividing it by 100.
Simple Interest Formula = (P x T x R)/100
Where P: principle amount, T: time, and R: Interest rate
For example, if you borrow $10,000 for one year at an annual interest rate of 10%, you will pay the interest of $1,000 and $11,000 in total.
Let’s create a simple program to calculate the simple interest in javascript. The code is straightforward.
// Function to Calculate Simple Interest in Javascript.
function calculateInterest(p, r, t) {
return (p*r*t) / 100
}
console.log(calculateInterest(10000, 10, 1))
1000
Let’s also create a function that will return the total payable amount (principle + interest).
Total Amount Formula:
A = P x (1 + RT)
function calculateTotalAmount(p, r, t) {
return p * (1 + ((r/100) * t))
}
console.log(calculateTotalAmount(10000, 10, 1))
11000
Let’s create an interactive calculator with the three input number fields (Principle, Rate of interest, Time in Years) and a button. On button click, total interest and amount will be displayed on the screen.
<html>
<head>
</head>
<body>
<input type="number" id="p" placeholder="Enter Principle amount">
<input type="number" id="r" placeholder="Enter Rate of interest">
<input type="number" id="t" placeholder="Enter Time in Years">
<button id="calculate">Calculate</button>
<p id="result"></p>
<script>
function calculateInterest(p, r, t) {
return (p*r*t) / 100
}
function calculateTotalAmount(p, r, t) {
return p * (1 + ((r/100) * t))
}
function calculate() {
const p = document.querySelector("#p").value;
const r = document.querySelector("#r").value;
const t = document.querySelector("#t").value;
const interest = calculateInterest(p, r, t);
const total = calculateTotalAmount(p, r, t);
const result = `Interest: $${interest}, Total Amt: $${total}`;
document.querySelector("#result").innerHTML = result
}
document.querySelector("#calculate").addEventListener("click", calculate);
</script>
</body>
</html>