Is there a string math evaluator in .NET?

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

    Actually there is kind of a built in one - you can use the XPath namespace! Although it requires that you reformat the string to confirm with XPath notation. I've used a method like this to handle simple expressions:

        public static double Evaluate(string expression)
        {
            var xsltExpression = 
                string.Format("number({0})", 
                    new Regex(@"([\+\-\*])").Replace(expression, " ${1} ")
                                            .Replace("/", " div ")
                                            .Replace("%", " mod "));
    
            return (double)new XPathDocument
                (new StringReader(""))
                    .CreateNavigator()
                    .Evaluate(xsltExpression);
        }
    

提交回复
热议问题