How to calculate total salary over a period of years with an annual raise each year in javascript

Viewed 44

I am trying to compute the total salary over a period of time where the user inputs their salary now, their annual raise percentage, their current age, and their retirement age. I need it to calculate the total amount they would make from their current age to their retirement age while also including the annual raise for each year. When I run it now with the following user inputs: Salary 150,000 , Annual raise 2% , current age 25 , retirement age 28 the output I get is 456,060 but the correct output is 459,060. This is the code I have so far. I need help on how to store the value from each for loop so it adds it in the next loop. Thank you in advance!

{ 
    num1 = this.getField("Salary").value;
    num2 = this.getField("Increase").value;
    num3 = this.getField("Age").value;
    num4 = this.getField("Retirement").value;
    num5 = num4 - num3 - 1        
    var answer = num1;
for(var i = 0; i < num5; i++) {
answer = answer + ((answer*num2)/100);
}
answer = num1 * num5 + answer;
this.getField("Income Value").value = answer;
}
1 Answers

You can simplify and at the same time clarify your calculation

var num1=150000, // income 
    num2=  2,    // yearly increase in percent
    num3= 25,    // starting age
    num4= 28,    // retirement age
    fact= 1+num2/100;  // yearly increase factor   

// As a one-liner, without a loop, you can do this:
console.log(num1*(fact**(num4-num3)-1)/(fact-1))
   
// Or, following your loop- based approach:
for(var answer=0,i=num4-num3;i--;num1*=fact) answer+=num1
console.log(answer)

The for loop now starts at answer=0 and increases it for each year of the candidate's employment with the current value of num1: the yearly salary that is multiplied by fact at the end of each loop cycle. The variable i starts at i=3 and is decremented after each loop check. The loop then stops as soon as i==0.

See here for the future value of an annuity calculation.

Related