Is there a string math evaluator in .NET?

前端 未结 16 1406
长情又很酷
长情又很酷 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: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(""))
                        .CreateNavigator()
                        .Evaluate(xsltExpression);
    // ReSharper restore PossibleNullReferenceException
            }
    
        }
    }
    

提交回复
热议问题