0

I am building a simple Javascript calculator that calculates strings by using eval(). There are a couple of issues that I am running into.

  1. If I run something like eval("023 + 11") that returns 30. Should I be expecting 24 instead?
  2. I have a option to convert a percentage into a decimal eval("025 * 0.01") that returns 0.21 when I am expecting 0.25
  3. Running certain numbers like eval("0.7 * 0.01") returns 0.006999999999 when I am expecting 0.007. Other times when I run eval("0.25 * 0.01") return 0.0025, which is correct.

When I deploy this, I am worried about other issues from eval() that might result in a incorrect calculation. Are there any other issues that users might encounter. Are there any better ways to build the calculator? How would I fix the issues I am having (I guess for inputs starting with 0 that's not a decimal I could strip the 0)?

imandy
  • 83
  • 6
  • 1
    Relevant: [Why JavaScript treats a number as octal if it has a leading zero](https://stackoverflow.com/q/37003770) | [Is floating point math broken?](https://stackoverflow.com/q/588004) – VLAZ Jun 02 '21 at 16:40
  • using `eval` is not good practise. better use `parseInt`, `parseFloat` and do with your arithmetic operation. [Read why?](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) – prasanth Jun 02 '21 at 16:41
  • Besides incorrect calculation, you should also be worried about people hacking your website and taking your entire server down, since you're using `eval`... – Heretic Monkey Jun 02 '21 at 16:43
  • Even more mundanely from security concerns, `eval` doesn't evaluate mathematical expressions but JS code. There is a difference. If you have `3 - + - + - 5` that's not a valid mathematical expression but it is valid JS code that returns `-2`. `3--` however, is not valid mathematical expression but because it's invalid code, you'd get a weird error for it. If you expect `3^2` to do "power of" then you'd get a surprise, since it's bitwise XOR. The power operator is `**` but it doesn't work with a negative base: `-3**2` is a syntax error. `eval` is full of potential problems. – VLAZ Jun 02 '21 at 17:11

0 Answers0