Is there a string math evaluator in .NET?

前端 未结 16 1853
长情又很酷
长情又很酷 2020-11-22 01:01

If I have a string with a valid math expression such as:

String s = \"1 + 2 * 7\";

Is there a built in library/function in .NET that will p

16条回答
  •  佛祖请我去吃肉
    2020-11-22 01:25

    You can use Math-Expression-Evaluator library that I am author of. It supports simple expressions such as 2.5+5.9, 17.89-2.47+7.16, 5/2/2+1.5*3+4.58, expressions with parentheses (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) and expressions with variables:

    var a = 6;
    var b = 4.32m;
    var c = 24.15m;
    var engine = new ExpressionEvaluator();
    engine.Evaluate("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))", new { a, b, c});
    

    You can also pass parameters as named variables:

    dynamic dynamicEngine = new ExpressionEvaluator();
    
    var a = 6;
    var b = 4.5m;
    var c = 2.6m;
    
    dynamicEngine.Evaluate("(c+b)*a", a: 6, b: 4.5, c: 2.6);
    

    It supports .Net Standard 2.0 so can be used from .Net Core as well as .Net Full Framework projects and it doesn't have any external dependencies.

提交回复
热议问题