Evaluate math expression from text

protected void Page_Load(object sender, System.EventArgs e)
{
 double OnePlusOne = EvaluateExpression("1+1");
 double SixMinusTwo = EvaluateExpression("6-2");
 double EightDividedByFour = EvaluateExpression("8/4");
 double FifteenSixteenths = EvaluateExpression("15/16");
 double RemainderOfFiveDividedByTwo = EvaluateExpression("5%2");
 double MultipleExpressions = EvaluateExpression("(1+1)*(6-2)-(8/4)/(15/16)");
 double InvalidOperation = EvaluateExpression("0/0");
}

public double EvaluateExpression(string ExpressionString)
{
 double ReturnValue = null;
 Data.DataTable ComputeDataTable = new Data.DataTable();
 try {
  ReturnValue = Convert.ToDouble(ComputeDataTable.Compute(ExpressionString, null));
  //Can only evaluate using the following arithmetic operations:
  //+ (addition), - (subtraction), * (multiplication), / (division), % (modulus)
 } catch {
 }
 return ReturnValue;
}

No comments:

Post a Comment