mep
mep

Reputation: 67

How to calculate interest javascript

I'm trying to create a function that returns the money I have after x years of interest.

var calculateInterest = function(total, year, rate) {
  (var interest = rate / 100 + 1;
  return parseFloat((total * Math.pow(interest, year)).toFixed(4))
}

console.log(calculateInterest(915, 13, 2));

I'm not getting it to work and I'm stuck! Any advice?

Upvotes: 1

Views: 9800

Answers (1)

Nate Barbettini
Nate Barbettini

Reputation: 53710

You were close. You don't need parentheses around var interest:

var calculateInterest = function(total, year, rate) {
  var interest = rate / 100 + 1;
  return parseFloat((total * Math.pow(interest, year)).toFixed(4));
}

var answer = calculateInterest(915, 13, 2);
console.log(answer);

I'd recommend cleaning it up a little to:

var calculateInterest = function(total, years, ratePercent, roundToPlaces) {
  var interestRate = ((ratePercent / 100) + 1);
  return (total * Math.pow(interestRate, years)).toFixed(roundToPlaces);
}

var answer = calculateInterest(915, 13, 2, 2);
console.log(answer);

You don't need parseFloat() if the variable is already a number (it's needed when you're parsing from a string, which is not the case here). I am adding a parameter to specify how many decimal places to round to is useful so you can control the output of the function.

Updated fiddle

Upvotes: 3

Related Questions