C# Equation and Formula Parser
An Equation and Formula Parser is a tool (or software component) that takes a mathematical expression written as text (like "2*x + 3 = 7") and analyzes, interprets, and often evaluates it.
A parser is a system that:
• Reads a formula or equation as a string
• Breaks it into meaningful parts (tokens)
• Builds a structured representation (like a tree)
• Optionally evaluates or manipulates it
When we use equation parsers?
Equation/Formula parsers are used whenever you need to process mathematical expressions dynamically instead of hardcoding logic.
Common use cases:
1. Calculators
• Scientific calculators
• Web-based calculators
2. Spreadsheets
• Excel formulas (=A1+B1*2)
• Google Sheets expressions
3. Programming languages
• Compilers and interpreters (e.g., Python, JavaScript engines)
4. Data analysis tools
• Dynamic formula evaluation
• KPI builders
5. Game engines
• Physics expressions
• Custom scripting systems
6. Business rule engines
• “If revenue > 1000 * tax_rate then approve”
Key Features of a Good Parser
Expression support
• Arithmetic: + - * /
• Exponentiation: ^
• Parentheses: ( )
Operator precedence
• Correct math order: () → ^ → * / → + -
Variables
Example:
• price * quantity + tax
Functions
Support for: sin(x), cos(x), max(a, b), sqrt(x)
Nested expressions
Example: (2 + (3 * (4 + 5)))
Evaluation modes
• immediate evaluation
• lazy evaluation
• symbolic manipulation (advanced systems like WolframAlpha)
Extensibility
Ability to add:
• custom operators
• custom functions
• domain-specific rules
C# Equation and Formula Parser Source Code
We will provide a stack solution written in c# to handle "Equation and Formula Parser" problem.
Here is the C# source code of an "Equation and Formula Parser" that is developed by my old friend Ahmed Yasin Koçulu.
void Main()
{
string input = "2-(3*(2-7)+4+5)*7";
System.Console.WriteLine(input + " = " + Calculate(input));
}
double Calculate(string input)
{
var list = Regex.Split(input, "([+*-/()])")
.Where(x => !string.IsNullOrWhiteSpace(x));
double result = 0;
Stack numStack = new Stack();
Stack opStack = new Stack();
bool fetchNumber = true;
foreach(var m in list)
{
if(m == "(")
{
opStack.Push(m);
}
else if(m == ")")
{
Walk(numStack, opStack, true);
}
else
{
if(fetchNumber)
{
double number = double.Parse(m.Trim());
numStack.Push(number);
}
else
{
if(m == "+" || m == "-")
Walk(numStack, opStack);
opStack.Push(m);
}
fetchNumber = !fetchNumber;
}
}
Walk(numStack, opStack);
result = numStack.Pop();
return result;
}
void Walk(Stack numStack, Stack opStack, bool close = false)
{
while(opStack.Count > 0 && numStack.Count > 1)
{
if(opStack.Peek() == "(")
{
if(close)
opStack.Pop();
break;
}
string operation = opStack.Pop();
double d2 = numStack.Pop();
double d1 = numStack.Pop();
double z1 = 0;
switch(operation)
{
case "+": z1 = d1 + d2; break;
case "-": z1 = d1 - d2; break;
case "*": z1 = d1 * d2; break;
case "/": z1 = d1 / d2; break;
}
numStack.Push(z1);
}
}