JavaScript Function for Calculating Annual Percentage Rate (APR Formula)
Fri, September 10, 2010 at 6:42 PM
Paul Cormier in Coding, Javascript, annual percentage rate, apr

Usually, whenever I need one of these helper-type functions, a quick Google Search usually turns up exactly what I need. However, when I needed a JavaScript function to calculate the Annual Percentage Rate (APR) on a home loan, it was nowhere to be found!

In this post is the function I wrote to calculate APR based on some formulas I did find. One of my requirements was that this formula needed to produce exactly the same result as the Excel RATE function that I frequently encountered while trying to find an APR function.

This function was designed for fixed monthly payments. It will not work for variable rate loans.

The JavaScript Annual Percentage Rate (APR) Function

<script type="text/javascript">
function calculateAPR(loanamount, numpayments, baseannualrate, costs){
	/* 
	By Paul Cormier - Sep 10, 2010 - http://webmasterymadesimple.com
	loanamount 	= the amount borrowed
	numpayments	= number of monthly payments e.g. 30 years = 360
	baserate	= the base percentage rate of the loan. A 5.25% Annual Rate should be passed in as 0.0525 NOT 5.25
	costs		= the loan closing costs e.g. origination fee, broker fees, etc.
	*/
	var rate = 	baseannualrate / 12;
	var totalmonthlypayment = ((loanamount+costs) * rate * Math.pow(1+rate,numpayments)) / (Math.pow(1+rate, numpayments)-1);
	var testrate = rate;
	var iteration = 1;
	var testresult = 0;
	//iterate until result = 0
	var testdiff = testrate;
	while (iteration <= 100) {
		testresult = ((testrate * Math.pow(1 + testrate, numpayments)) / (Math.pow(1 + testrate, numpayments) - 1)) - (totalmonthlypayment / loanamount);
		if (Math.abs(testresult) < 0.0000001) break;
		if (testresult < 0) testrate += testdiff;
		else testrate -= testdiff;
		testdiff = testdiff / 2;
		iteration++;
	}
	testrate = testrate * 12;
	return testrate.toFixed(6);
}
</script>

NOTE: I assume no liability or responsibility for the accuracy or results produced by this function. It is up to you to test and verify that it returns the desired results. You are free to do whatever you wish with the function.

If you found this function to be useful and saved you some time and effort, feel free to donate to my beer fund using the PayPal link below.

Article originally appeared on (http://www.webmasterymadesimple.com/).
See website for complete article licensing information.