Is there a string math evaluator in .NET?

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

提交回复
热议问题