admin管理员组

文章数量:1415139

suppose I have the following code:

    var str = "4*(3)^2/1"

Is the simplest solution just to make a stack of the operators and solve with postfix notation? Or is there a really basic solution I'm missing.

Additionally how can I adapt if I'm using log, ln, sin, cos, and tan?

suppose I have the following code:

    var str = "4*(3)^2/1"

Is the simplest solution just to make a stack of the operators and solve with postfix notation? Or is there a really basic solution I'm missing.

Additionally how can I adapt if I'm using log, ln, sin, cos, and tan?

Share Improve this question asked Sep 2, 2017 at 19:49 Jamie AlizadehJamie Alizadeh 1591 silver badge7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Sorry to respond to my own question, but the easiest solution is using math.js

    var ans = math.eval(str);

The simplest yet a bit dangerous so you may have to validate (clean) an expression before evaluating is using eval (for exponent-operator ^, replace it with the exponent-operator in JavaScript **):

var str="4*(3)^2/1".replace(/\^/g,'**');
console.log(eval(str));

And for special functions such as sin, cos, exp and so on, create a function of your own using the corresponding predefined function in JavaScript:

var str="4*(3)^2/1+(exp(5)*cos(14)^(1/sin(13)))^2".replace(/\^/g,'**');
function sin(x) { return Math.sin(x) }
function cos(x) { return Math.cos(x) }
// so on
function exp(x) { return Math.exp(x) }
console.log(eval(str));

You do not need postfix notation. You can use eval method.

var str = "4*(3)^2/1";
console.log(str);
console.log(eval(str));

Also, another solution is using javascript-expression-evaluator which allows you to do stuff like:

Parser.evaluate("2 ^ x", { x: 4 });

本文标签: mathSolve an arithmetic string in javascriptStack Overflow