Javascript Calculator Issue with subtracting and multiplying

Code Pen
When I subtract values instead of subtracting them it adds them. Then when I multiply the values it returns NAN.

Thank you!

since you are calculating values like below and not using eval(), you need to sanitize the values of data.currentValue and display.value.

total = parseFloat(data.currentValue) - parseFloat(display.value);

Let me explain it to you by an example. Let say I am trying to calculate 5 -5 which should equal to 0 but your calculator gives me 10!

The reason is when I press 5 and then negative sign and 5 again, your data.currentValue = “05” and display.value = “-5”. So when you do the calculation like above, it will be below which is mathematically correct but not your expected result.

5 - (-5) = 10

I saw few other bugs as well so I suggest you review your whole code and start working one bug at a time. Also I suggest you look into eval() which will be lot easier to do calculations.

1 Like