JSFiddle - React, Tailwind, and code Playground

by Justin

JavaScript

function calcAPR(loanamount, numpayments, baseannualrate, costs){
	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);
}

$('body').append(calcAPR(475000,360,0.05, (10799)));