Created
March 4, 2020 19:48
-
-
Save manishprajapatidev/c0b29f08768308a9e45e5d3d9d968ed4 to your computer and use it in GitHub Desktop.
EMI Calculator for Loans, Monthly breakdown of EMI in Principal and Interest components - www.koffeewithkode.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
By: Manish (www.koffeewithkode.com) | |
*/ | |
function calculateEMI(principal, rate_percent, time_in_months, precision) { | |
var EMI; | |
var rate_per_month = (rate_percent / 12) / 100; //divide the rate by 100 and 12 | |
var numr = Math.pow((1 + rate_per_month), time_in_months); | |
var denr = (Math.pow((1 + rate_per_month), time_in_months) - 1); | |
EMI = principal * rate_per_month * (numr / denr); | |
//round the EMI to two decimal points | |
EMI = EMI.toFixed(precision); | |
var total_payment = EMI * time_in_months; | |
var total_interest = total_payment - principal; | |
var data_obj = []; | |
var principal_by_month = principal; | |
// loop through each month and calculate | |
// each months principal component and the interest component | |
for (var i = 1; i <= time_in_months; i++) { | |
var each_months_principal, each_months_interest; | |
each_months_interest = principal_by_month * rate_per_month; | |
var principal_component = EMI - each_months_interest; | |
var interest_component = each_months_interest; | |
var balance_principal = principal_by_month - principal_component; | |
if (balance_principal < 0) { | |
balance_principal = 0; | |
} | |
var single_month_data = [principal_component, interest_component, balance_principal]; | |
data_obj.push(single_month_data); | |
principal_by_month = principal_by_month - principal_component; | |
} | |
var result = new Array(); | |
result['principal'] = principal; | |
result['time_in_months'] = time_in_months; | |
result['rate_percent'] = rate_percent; | |
result['emi'] = EMI; | |
result['total_interest'] = total_interest.toFixed(precision); | |
result['total_payment'] = total_payment.toFixed(precision); | |
result['data_obj'] = data_obj; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment