Mathematical evaluation of string Equations
In many cases there come the situation where we need to store equation in data store and calculate it based at run time. Let say we have an entry in DB as "Premium*50/100" for calculating some fees in policy creation.So at run time we should replace Premium with Premium value of that particular policy.
Say Premium =100;
Now we sill call Evaluate("100*50/100").
Mathematical string expression can be evaluate in c# using Stack.
C#
public static double Evaluate(string input)
{
String expression = "(" + input + ")";
Stack<String> operators = new Stack<String>();
Stack<Double> values = new Stack<Double>();
for (int i = 0; i < expression.Length; i++)
{
String str = expression.Substring(i, 1);
String prevStr = string.Empty; if (i > 1) prevStr = expression.Substring(i - 1, 1);
if (str.Equals("(")) { }
else if (str.Equals("+")) operators.Push(str);
else if (str.Equals("-")) operators.Push(str);
else if (str.Equals("*")) operators.Push(str);
else if (str.Equals("/")) operators.Push(str);
else if (str.Equals("sqrt")) operators.Push(str);
else if (str.Equals(")"))
{
int count = operators.Count;
while (count > 0)
{
String op = operators.Pop(); double v = values.Pop();
if (op.Equals("+")) v = values.Pop() + v;
else if (op.Equals("-")) v = values.Pop() - v;
else if (op.Equals("*")) v = values.Pop() * v;
else if (op.Equals("/")) v = values.Pop() / v;
else if (op.Equals("sqrt")) v = Math.Sqrt(v); values.Push(v); count--;
}
}
else
{
if (IsDigit(prevStr)) { double val = values.Pop(); values.Push(val * 10 + Double.Parse(str)); }
else values.Push(Double.Parse(str));
}
}
return values.Pop();
}
private static bool IsDigit(string str)
{
int temp;
if (int.TryParse(str, out temp)) return
true;
else return false;
}
Comments
Post a Comment