/// <summary> /// Calculates the specified expression. /// 计算器,计算数学表达式的值 /// </summary> /// <param name="expression"> 1+2+(1*3)</param> /// <returns></returns> public static string Calculate(string expression) { Token token = new Kooboo.Common.Dynamic.Calculator.Parser.Token(expression); Evaluator evaluator = new Evaluator(token); string value; string errorMsg; if (!evaluator.Evaluate(out value, out errorMsg)) { throw new CalculateExpression(errorMsg); } return value; }
private bool Eval(Parser.TokenItems Parameters, out Parser.TokenItem Result, out string ErrorMsg) { // initialize the outgoing variables ErrorMsg = ""; Result = null; // make sure we have at least 1 parameter if (Parameters.Count != 1) { ErrorMsg = "Eval[] Operand Function requires 1 parameter."; return false; } // get the expression to be evaluated string expression = Support.DataTypeCheck.RemoveTextQuotes(Parameters[0].TokenName); // create the tokens Parser.Token tokens = new Parser.Token(expression); if (tokens.AnyErrors == true) { ErrorMsg = tokens.LastErrorMessage; return false; } // create the evaluator object Evaluator e = new Evaluator(tokens); string value = ""; if (e.Evaluate(out value, out ErrorMsg) == false) return false; if (Support.DataTypeCheck.IsInteger(value) == true) Result = new Parser.TokenItem(value, Parser.TokenType.Token_Operand, Parser.TokenDataType.Token_DataType_Int, false); else if (Support.DataTypeCheck.IsDouble(value) == true) Result = new Parser.TokenItem(value, Parser.TokenType.Token_Operand, Parser.TokenDataType.Token_DataType_Double, false); else if (Support.DataTypeCheck.IsDate(value) == true) Result = new Parser.TokenItem(value, Parser.TokenType.Token_Operand, Parser.TokenDataType.Token_DataType_Date, false); else Result = new Parser.TokenItem(value, Parser.TokenType.Token_Operand, Parser.TokenDataType.Token_DataType_String, false); return true; }