1

I'm trying to create a JavaScript version of this equation that I got working in Excel:

Excel version:

10000*(1+0.06)^30+6000*(((1+0.06)^30-1)/0.06)

This calculates out to 531784.029

JavaScript version:

console.log(10000*(1+0.06)^30+6000*(((1+0.06)^30-1)/0.06));

Returns: 2789622

Or if I try to use Math.pow():

console.log(10000*(Math.pow(1+.06),30)+6000*(Math.pow((1+.06),30-1)/.06));

Returns: 841838.7898974773

I'm completely stumped after about 6 hours. How do I recreate that excel calculation and get the same number?

j08691
  • 190,436
  • 28
  • 232
  • 252
  • Is there a reason that you're not shortcutting the 30-1 and 1+0.06? – Rowland Shaw Oct 05 '16 at 15:52
  • `(1+0.06)^30` are you sure that's correct? the `^` does an XOR in JavaScript, not power, like in Excel – VLAZ Oct 05 '16 at 15:52
  • Also, in your second try `(Math.pow(1+.06),30)` the brackets are wrong. What that would do is _evaluate_ `Math.pow(1+.06)` then discard it and return `30` due to the comma - you probably want `Math.pow(1+.06,30)` – VLAZ Oct 05 '16 at 15:54
  • I'm using (1+.06) because once I've got this worked out that ".06" will actually be variable coming from an input. It's an interest rate. – Matthew MacMillan Oct 05 '16 at 16:15

1 Answers1

3

For the same behavior as in excel you just have the wrong order of operators and wrong parameters to the Math.powfunction in js, it should be like this:

console.log(10000*(Math.pow(1+.06,30))+6000*((Math.pow(1+.06,30)-1)/0.06));

the ^ operator in javascript is not the same as in excel, in js it means a bitwise xor operation, while in excel it means the same as the Math.pow.

The Math.powfunction in javascript takes two parameters, so for example to make the same operation as in excel 1.06^30 you would do Math.pow(1.06,30)in javascript.

by the way maybe is just something you put for the example but you dont need to add 1+.06you could just write 1.06:

 console.log(10000*(Math.pow(1.06,30))+6000*((Math.pow(1.06,30)-1)/0.06));
Frank Orellana
  • 1,560
  • 1
  • 19
  • 26
  • 1
    I was just about to hit Post saying more or less the same but you were just around 2 seconds faster than me :) – VLAZ Oct 05 '16 at 16:03
  • @vlaz Thanks for the js snippet code... I was wondering how to do that – Frank Orellana Oct 05 '16 at 16:06
  • 1
    It's quite embarassing, really but it took me, like _a month_ to realise there is a button in the editor when you're posting. It's the little page with `<>` in it icon which is pretty much in the middle of the buttons. – VLAZ Oct 05 '16 at 16:14
  • Also, in case anyone else ever needs this, it's an equation for compound interest over 30 years at 6% interest with $6000 being added at the END of each year. – Matthew MacMillan Oct 05 '16 at 16:20