Real World Example

EMI Calculator

Loan apps (Bajaj Finserv, bank websites) show an EMI calculator. The formula is EMI = P x r x (1+r)^n / ((1+r)^n - 1) where P is the principal, r is the monthly interest rate and n is the number of months.

Example

public class Main {
    public static void main(String[] args) {
        double principal = 500000;      // Rs. 5 lakh
        double annualRate = 10.5;       // percent per year
        int months = 36;

        double r = annualRate / 12 / 100;
        double factor = Math.pow(1 + r, months);
        double emi = principal * r * factor / (factor - 1);
        double totalPaid = emi * months;

        System.out.printf("EMI            : Rs. %.2f%n", emi);
        System.out.printf("Total payment  : Rs. %.2f%n", totalPaid);
        System.out.printf("Total interest : Rs. %.2f%n", totalPaid - principal);
        System.out.println("Rounded EMI    : Rs. " + Math.round(emi));
    }
}

Output

EMI            : Rs. 16251.22
Total payment  : Rs. 585043.98
Total interest : Rs. 85043.98
Rounded EMI    : Rs. 16251