Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2272
我在风中等你
我在风中等你 2020-11-22 03:34

How do I parse and evaluate a mathematical expression in a string (e.g. \'1+1\') without invoking eval(string) to yield its numerical value?

<
16条回答
  •  时光取名叫无心
    2020-11-22 04:18

    I created BigEval for the same purpose.
    In solving expressions, it performs exactly same as Eval() and supports operators like %, ^, &, ** (power) and ! (factorial). You are also allowed to use functions and constants (or say variables) inside the expression. The expression is solved in PEMDAS order which is common in programming languages including JavaScript.

    var Obj = new BigEval();
    var result = Obj.exec("5! + 6.6e3 * (PI + E)"); // 38795.17158152233
    var result2 = Obj.exec("sin(45 * deg)**2 + cos(pi / 4)**2"); // 1
    var result3 = Obj.exec("0 & -7 ^ -7 - 0%1 + 6%2"); //-7
    

    It can also be made to use those Big Number libraries for arithmetic in case you are dealing with numbers with arbitrary precision.

提交回复
热议问题