Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active August 29, 2015 14:17
Show Gist options
  • Save kjbrum/e833c027a9cd564f4b84 to your computer and use it in GitHub Desktop.
Save kjbrum/e833c027a9cd564f4b84 to your computer and use it in GitHub Desktop.
Calculate the monthly payments for paying off a loan
/**
* Calculate the monthly payments for paying off a loan
* Source: http://www.1728.org/loanform.htm
*
* @param integer apr APR of the loan
* @param integer term Length of repaying the loan in months
* @param integer loanAmount Amount that is being borrowed
* @return integer The monthly payments amount
*/
function calculateMonthlyPayments(apr, term, loanAmount) {
var monthlyPayments = 0,
rate = apr / 1200;
// Return false if one of the variables isn't a number
if(isNaN(apr) || isNaN(term) || isNaN(loanAmount)) {
return false;
}
// Calculate the payment differently if the apr is 0
if(apr == 0) {
monthlyPayments = loanAmount / term;
} else {
monthlyPayments = (rate + (rate / (Math.pow((rate + 1), term) - 1))) * loanAmount;
}
// If we get a negative amount, return 0
if(monthlyPayments <= 0) {
return '0';
}
// Return the calculated monthly payment
return Math.round(monthlyPayments);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment