Skip to main content

JavaScript Interest Loan Calculator Algorithm

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

It using a calculation of % interest which using logarithms to calculate the principle payment/total interest and how long it will take to pay off the loan given a borrow amount and a monthly payment amount

//FORMULA FOR CALUCLATING INTEREST RATE
//p = x*(1 - (1+r)^-n)/r

var interest = 15, rate = interest/100, principal = 1000, payment = 100, noofpay = 12;

var nper1 = Math.log((1-((principal/payment) * (rate/noofpay))));
var nper2 = Math.log((1+(rate/noofpay)));
nper = -(nper1/nper2);
interestpaid=payment*nper-principal;
nper = -Math.round((nper1/nper2));
nyear=Math.floor(nper/12);
nmonth=nper%12;
if (nper>0)
{
    if (nmonth==0)
    {
        period=nyear+" Year(s)";
    }
    else
    {
        period=nyear+" Year(s) and "+nmonth+" Month(s)";
    }
}
else
{
    period="Invalid Values";
    interestpaid=0;
}

console.log("Montly Payments: " + period + ", Total Interest Paid: " + interestpaid.toFixed(2));

Into a function with parameters passed in:

//the price calculation formula
//@return the price and length of time
function calculate(interest, principal, payment)
{
    //get data
    var calcElem = $('#calc');

    //FORMULA FOR CALUCLATING INTEREST RATE
    //p = x*(1 - (1+r)^-n)/r

    var rate = interest/100, noofpay = 12;

    var nper1 = Math.log((1-((principal/payment) * (rate/noofpay))));
    var nper2 = Math.log((1+(rate/noofpay)));
    nper = -(nper1/nper2);
    interestpaid=payment*nper-principal;
    nper = -Math.round((nper1/nper2));
    nyear=Math.floor(nper/12);
    nmonth=nper%12;
    if (nper>0)
    {
        if (nmonth==0)
        {
            period=nyear+" Year(s)";
        }
        else
        {
            period=nyear+" Year(s) and "+nmonth+" Month(s)";
        }
    }
    else
    {
        period="Invalid Values";
        interestpaid=0;
    }

    //console.log("Montly Payments: " + period + ", Total Interest Paid: " + interestpaid.toFixed(2));

    var priceData = {
        price : '$'+this.formatCurrency(interestpaid+owe),
        interest : '$'+this.formatCurrency(interestpaid),
        time  : period
    }
    return priceData;
}

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!

Latest Remote Jobs