0

I'm trying to get the following Excel sum working in Javascript.

=H21*(1+H22)*(1+H23)

H21 is a base price like 6.4 H22 and H23 are a negative percentage like '-15%'.

H22 and H23 come from range sliders so I have them like '-15'.

For now I have:

let price = H21*(1+H22)*(1+H23);

Adding % signs obviously don't work. Why does this work in Excel and not in Javascript and how can I re-factor to do this in Javascript. Any lead on documentation would also be very nice!

2
  • 1
    Why does this work in Excel and not in Javascript That's like saying, why do I have to change gear in a manual car, and I don't have to in an automatic. Percent, means per 100, or IOW: divide by 100. H22/100 Commented Mar 27, 2018 at 14:14
  • 1
    In Javascript, % is used for Modulo - so, the Javascript 5%2 is the same as the Excel =MOD(5,2), while in Excel % means "Divide by 100 and change General formatting to Percentage formatting" - so Excel 2*15% is Javascript's 2*15/100 Commented Mar 27, 2018 at 14:22

1 Answer 1

1

A percentage can be expressed as a float from 0-1, so I think you could just divide your percentage figures (H22 + H23) by 100:

let price = H21*(1+(H22/100))*(1+(H23/100));

Using numbers with % symbols in JS won't work, because the sum will cast them as floats by dropping anything that isn't valid:

parseInt('15%') // 15

Excel is seeing the % and doing something a bit more clever (which I didn't previously know about).

Sign up to request clarification or add additional context in comments.

4 Comments

Excel is slightly clever, but not completely clever - =10+15% will output 1015% rather than 11.5. But, while Excel doesn't know what to do with a permille symbol (‰) or permyriad/basis point (‱), you can chain % symbols: =5% is 0.05 and =5%% is 0.0005 which is the same as basis point (frequently used in finance e.g. for loans/bonds)
@Chronocidal - Did not know that %% worked- thanks. But why should 10+15%=11.5 rather than 10.15 =1015%?
@CharlesWilliams If you use a decent calculator, then "10+15%" is treated as "10*1.15" - i.e. "10 + (10*15%)". What would you say 15% more than 10 was?
@AdamHopkinson Thanks! Was way to focused on the Excel formula. Feeling a bit simple now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.