Is there a string math evaluator in .NET?

前端 未结 16 1437
长情又很酷
长情又很酷 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:18

    Have you seen http://ncalc.codeplex.com ?

    It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:

    Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)"); 
    
      e.Parameters["Pi2"] = new Expression("Pi * Pi"); 
      e.Parameters["X"] = 10; 
    
      e.EvaluateParameter += delegate(string name, ParameterArgs args) 
        { 
          if (name == "Pi") 
          args.Result = 3.14; 
        }; 
    
      Debug.Assert(117.07 == e.Evaluate()); 
    

    It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.

    0 讨论(0)
  • 2020-11-22 01:23
    namespace CalcExp
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                double res = Evaluate("4+5/2-1");
    
                Console.WriteLine(res);
    
            }
    
            public static double Evaluate(string expression)
            {
                var xsltExpression =
                    string.Format("number({0})",
                        new Regex(@"([\+\-\*])").Replace(expression, " ${1} ")
                                                .Replace("/", " div ")
                                                .Replace("%", " mod "));
    
    // ReSharper disable PossibleNullReferenceException
                return (double)new XPathDocument
                    (new StringReader("<r/>"))
                        .CreateNavigator()
                        .Evaluate(xsltExpression);
    // ReSharper restore PossibleNullReferenceException
            }
    
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 01:26

    You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)

    Dim sc As New MSScriptControl.ScriptControl()
    sc.Language = "VBScript"
    Dim expression As String = "1 + 2 * 7"
    Dim result As Double = sc.Eval(expression)
    

    Edit - C# version.

    MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
    sc.Language = "VBScript";
    string expression = "1 + 2 * 7";
    object result = sc.Eval(expression);            
    MessageBox.Show(result.ToString());
    

    Edit - The ScriptControl is a COM object. In the "Add reference" dialog of the project select the "COM" tab and scroll down to "Microsoft Script Control 1.0" and select ok.

    0 讨论(0)
  • 2020-11-22 01:31

    If you need very simple thing you can use the DataTable :-)

    Dim dt As New DataTable
    dt.Columns.Add("A", GetType(Integer))
    dt.Columns.Add("B", GetType(Integer))
    dt.Columns.Add("C", GetType(Integer))
    dt.Rows.Add(New Object() {12, 13, DBNull.Value})
    
    Dim boolResult As Boolean = dt.Select("A>B-2").Length > 0
    
    dt.Columns.Add("result", GetType(Integer), "A+B*2+ISNULL(C,0)")
    Dim valResult As Object = dt.Rows(0)("result")
    
    0 讨论(0)
  • 2020-11-22 01:33

    Strange that this famous and old question has not an answer that suggests the builtin DataTable.Compute-"trick". Here it is.

    double result = Convert.ToDouble(new DataTable().Compute("1 + 2 * 7", null));
    

    The following arithmetic operators are supported in expressions:

    + (addition)
    - (subtraction)
    * (multiplication)
    / (division)
    % (modulus)
    

    More informations: DataColumn.Expression at Expression Syntax.

    0 讨论(0)
提交回复
热议问题