Search code examples
javascriptangularjsecmascript-5

Converting formula to JavaScript


I am trying to build out a "How Much car can I afford" calculator that takes three arguments: Monthly Payment, interest Rate, and loan length. The three values are then calculated to present to user with a car value they can afford based off the data they entered. I was given then following formula:

CarValue = (MONTHLY PAYMENT * (1-(1+(INTEREST RATE / 12)) ^ -TERM)) / (RATE / 12)

using ECMAScript 5 I'm trying to convert this formula to JavaScript and its giving me wild results:

var monthlyPayment = $scope.model.howMuchCanIAfford.monthlyPayment;
var interestRate = $scope.model.howMuchCanIAfford.interestRate;
var loanLength = $scope.model.howMuchCanIAfford.loanLength;

var monthlyAmount = (monthlyPayment * (Math.pow(1-((1+(interestRate / 12))), (-1 * loanLength)))) / (interestRate / 12);

Example Data:

monthlyPayment = 700
interestRate = 9.2
loanLength = 84

output: $4,503,380,362,412.83

Obviously the output amount is wildly off and I'm unsure if my formula conversion is the issue or the original formula I was given is wrong.


Solution

  • It should be:

    var monthlyAmount = (monthlyPayment * ( 1- Math.pow( (1+(interestRate / 12)), (-1 * loanLength) ))) / (interestRate / 12); 
    

    In the original formula the -1 is outside of parentheses that are raised to a power.