Skip to main content
CodingMarble

Code snippets

Build an EMI Calculator in JavaScript (With Schedule)

An EMI calculator applies one formula, EMI = P * r * (1+r)^n / ((1+r)^n - 1), where r is the annual rate divided by 12 and by 100 and n is the number of months. This tutorial turns it into a validated function, an amortisation schedule and a working HTML form, with every printed number checked by running the code.

By CodingMarble · Published · 5 min read

Lines of code on a computer screen
Photo: Chris Ried on Unsplash

The EMI formula and what each symbol means

EMI stands for equated monthly instalment: the fixed amount a borrower pays each month so that a loan is fully repaid at the end of the tenure. Most loans quote interest on the reducing balance, meaning interest is charged only on the amount still owed, which falls as instalments are paid. The standard formula for that arrangement is EMI = P * r * (1 + r)^n / ((1 + r)^n - 1).

  • P is the principal, the amount borrowed.
  • r is the monthly rate as a fraction. If the quoted annual rate is 10 percent, then r = 10 / 12 / 100, which is about 0.008333.
  • n is the number of monthly instalments, so a five-year loan has n = 60.

The formula comes from requiring that the present value of all n equal payments equals the principal. You do not need to derive it to use it, but understanding that it is a geometric series explains why the (1 + r)^n term appears twice and why the formula breaks when r is zero: the denominator becomes zero. We handle that case explicitly below.

A worked example makes the later code easy to check. Take a principal of 100000, an annual rate of 10 and a tenure of 12 months. Then r is 0.008333, (1 + r)^12 is about 1.1047, and the EMI works out to 8791.59 when rounded to two decimals. Over 12 payments the borrower repays about 105499.06, so the total interest is about 5499.06.

A validated EMI function

The function below does three jobs: it rejects inputs that would produce nonsense, handles the zero-interest case, and applies the formula. Validation matters because a calculator is used by people typing quickly. Empty fields become NaN, a negative tenure produces a negative or infinite result, and a fractional number of months has no meaning for monthly instalments.

JavaScript· calculateEmi: validation, zero-interest case and the formula
export function calculateEmi(principal, annualRate, months) {
  if (![principal, annualRate, months].every(Number.isFinite)) {
    throw new Error("Enter numbers only.");
  }
  if (principal <= 0) throw new Error("Principal must be above zero.");
  if (annualRate < 0) throw new Error("Rate cannot be negative.");
  if (!Number.isInteger(months) || months < 1) {
    throw new Error("Tenure must be a whole number of months.");
  }

  if (annualRate === 0) return principal / months;

  const r = annualRate / 12 / 100;
  const growth = Math.pow(1 + r, months);
  return (principal * r * growth) / (growth - 1);
}

// Quick checks
console.log(calculateEmi(100000, 10, 12).toFixed(2)); // 8791.59
console.log(calculateEmi(120000, 0, 12)); // 10000

Number.isFinite rejects NaN and Infinity, and also rejects strings, so the caller must convert form values first. With zero interest the loan is simply split into equal parts, so principal divided by months is correct. Running the two checks above prints 8791.59 and 10000.

Keep full precision inside calculations and round only for display. If you round the monthly rate or the EMI early and then multiply by the tenure, small errors accumulate. A common mistake is to treat the annual rate as if it were already monthly, or to divide by 12 but forget to divide by 100. Both are caught by comparing against the worked example.

Building an amortisation schedule

An amortisation schedule lists each month's interest, principal repayment and remaining balance. It shows something the headline EMI hides: early instalments are mostly interest, and later ones are mostly principal. For each month the interest is the opening balance times r, the principal part is the EMI minus that interest, and the new balance is the old balance minus the principal part.

JavaScript· buildSchedule: month-by-month interest, principal and balance
import { calculateEmi } from "./emi.js";

export function buildSchedule(principal, annualRate, months) {
  const emi = calculateEmi(principal, annualRate, months);
  const r = annualRate / 12 / 100;
  const rows = [];
  let balance = principal;

  for (let month = 1; month <= months; month++) {
    const interest = balance * r;
    let principalPart = emi - interest;
    if (month === months) principalPart = balance; // absorb rounding drift
    balance = month === months ? 0 : balance - principalPart;
    rows.push({
      month,
      interest,
      principalPart,
      payment: principalPart + interest,
      balance,
    });
  }
  return rows;
}

const rows = buildSchedule(100000, 10, 12);
console.log(rows[0].interest.toFixed(2)); // 833.33
console.log(rows[0].principalPart.toFixed(2)); // 7958.26
console.log(rows[11].payment.toFixed(2)); // 8791.59
const totalInterest = rows.reduce((sum, row) => sum + row.interest, 0);
console.log(totalInterest.toFixed(2)); // 5499.06

In month one the interest is 100000 times 0.008333, which is 833.33, so only 7958.26 of the first instalment reduces the debt. By month twelve the interest has shrunk to about 72.66. The final row sets the principal part to whatever balance remains, because floating-point arithmetic leaves a tiny residue after many subtractions; this forces the closing balance to exactly zero. In the output above, the sum of interest over 12 months matches the total interest computed from the EMI, 5499.06.

Wiring up a form and formatting with Intl.NumberFormat

Now connect the logic to a page. The HTML uses a form with number inputs, which gives mobile users the numeric keypad, and an output region marked aria-live so screen readers announce updated results. The script reads values, converts them to numbers, calls the function and prints the result. Errors from validation are shown inline instead of crashing.

HTML· Minimal form and result area
<form id="emi-form" novalidate>
  <label>Principal
    <input id="principal" type="number" min="1" step="any" value="500000" />
  </label>
  <label>Annual rate (%)
    <input id="rate" type="number" min="0" step="0.01" value="9" />
  </label>
  <label>Tenure (months)
    <input id="months" type="number" min="1" step="1" value="60" />
  </label>
  <button type="submit">Calculate</button>
</form>
<div id="result" aria-live="polite"></div>
<script type="module" src="./app.js"></script>
JavaScript· app.js: read inputs, calculate, format with Intl.NumberFormat
import { calculateEmi } from "./emi.js";

const fmt = new Intl.NumberFormat("en-IN", {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

const form = document.querySelector("#emi-form");
const result = document.querySelector("#result");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const principal = Number(form.principal.value);
  const rate = Number(form.rate.value);
  const months = Number(form.months.value);
  try {
    const emi = calculateEmi(principal, rate, months);
    const total = emi * months;
    result.textContent =
      "Monthly instalment: " + fmt.format(emi) +
      ". Total repayment: " + fmt.format(total) +
      ". Total interest: " + fmt.format(total - principal) + ".";
  } catch (err) {
    result.textContent = err.message;
  }
});

Intl.NumberFormat with the en-IN locale groups digits in the Indian style, so 1234567.891 prints as 12,34,567.89 and the example EMI prints as 8,791.59. Pass a different locale for other audiences; the formatter, not your own string manipulation, should own grouping. Note that Number of an empty input is 0, which the validator rejects as a principal, so a blank field gives a clear message. For a principal of 500000, a rate of 9 and 60 months, the form shows an instalment of about 10379.18 and total interest of about 122750.66.

Why you should always show the total interest

Many calculators display only the monthly instalment, because it is the figure people compare against their budget. That hides the cost of the loan. Stretching the tenure lowers the instalment while raising the total paid, and users deserve to see that trade-off. Using the same formula, a principal of 500000 at a rate of 9 costs about 122750.66 in interest over 60 months, but about 260054.64 over 120 months, even though the monthly figure drops from roughly 10379.18 to roughly 6333.79.

Showing total repayment and total interest beside the instalment lets people compare tenures honestly. A small table that updates for a few tenures, or the amortisation schedule collapsed behind a disclosure element, adds depth without clutter. Label results as estimates: real lenders may add processing fees, charge on a daily balance, or round instalments differently, so the number a bank quotes can differ slightly from a generic calculator.

Testing and common mistakes

Test with values you can verify independently. The zero-rate case should equal principal divided by months. The sum of all payments in the schedule should equal the EMI times months. The final balance should be exactly zero. Interest in month one should equal the principal times the monthly rate. And the invalid cases should throw: negative principal, a fractional tenure, a blank field.

  • Passing strings from inputs without converting them to numbers, so 'principal + something' concatenates.
  • Using the annual rate directly, or dividing by 12 but not by 100.
  • Rounding at every step and drifting away from the true figure.
  • Entering tenure in years but treating it as months; if you offer years, multiply by 12 before calling the function.
  • Forgetting the zero-interest branch and displaying NaN or Infinity.

If you would like to see a finished calculator before building your own, CodingMarble runs free calculators at calculator.codingmarble.com. Compare its results with your own function using the worked example above; if the numbers disagree, check the rate conversion first.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.