Arnold Oosterom
Arnold Oosterom

Reputation: 127

Excel formula with % in Javascript

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!

Upvotes: 0

Views: 62

Answers (1)

Adam Hopkinson
Adam Hopkinson

Reputation: 28795

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).

Upvotes: 1

Related Questions