JSFiddle - React, Tailwind, and code Playground

by cormip

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); }