Home > Articles > Web Development > Ajax and JavaScript

  • Print
  • + Share This
From the author of

Calculating a Loan Balance

To calculate how much principal is remaining on an outstanding loan, use this formula:

PV = PMT x (1 – (1 + IR)NP) / IR

In this case, NP is the number of payments left on the loan. Here's the JavaScript equivalent:

PV = PMT * (1 - Math.pow(1 + IR, -NP)) / IR

Listing 2 shows you how to use this expression. The example uses a monthly payment of $200, an annual interest rate of 9%, and a remaining term of two years.

Listing 2: Calculating a Loan Balance

<script language="JavaScript" type="text/javascript">
<!--

function calculate_balance(PMT, IR, NP) {
  var PV = PMT * (1 - Math.pow(1 + IR, -NP)) / IR
  return round_decimals(PV, 2)
}

function round_decimals(original_number, decimals) {
  var result1 = original_number * Math.pow(10, decimals)
  var result2 = Math.round(result1)
  var result3 = result2 / Math.pow(10, decimals)
  return (result3)
}

var monthly_payment = 200
var interest_rate = 0.09
var term_remaining = 2
var loan_balance = calculate_balance(monthly_payment, interest_rate / 12, 
          term_remaining * 12)

alert("Monthly payment:\t$" + monthly_payment + "\n" +
   "Annual interest rate:\t" + interest_rate * 100 + "%\n" +
   "Term remaining:\t" + term_remaining + " years\n\n" +
   "Remaining balance:\t$" + loan_balance)

//-->
</script>
  • + Share This
  • 🔖 Save To Your Account