This project is read-only.

Project Description

A library designed to read user entered string and evaluate it as an math expression.
- Able to understand all the operators that Excel users are used to.
- Expose the System.Math functions, but allow additional functions to be added by API
- Allow variables access via delegate

Quick Start

Quick Evaluation of a String

To evaluate a single expression and return a value:

object output = JDunkerley.Parser.Parser.Evaluate("1+6%*(90/365)");

By default, the System.Math functions are not included To register these you need to call:

JDunkerley.Parser.Parser.RegisterMathFunctions();
object output = JDunkerley.Parser.Parser.Evaluate("Sin(90/360*2*PI)");

Using Variables

If an expression contains a variable a delegate can be passed to the Evaluate function to allow it obtain a value for the variable. For example:

JDunkerley.Parser.Parser.RegisterMathFunctions();
Dictionary<string, double> args = new Dictionary<string, double>();
args["R"] = 100;
args["T"] = 35;
object output = JDunkerley.Parser.Parser.Evaluate("R*Sin(T/360*2*PI)", (name) => { return args.ContainsKey(name) ? args[name] : double.NaN; });

Repeat Evaluation

If you want to evaluate an expression repeatedly, then you should get the IComponent representing the expression:

For example:

JDunkerley.Parser.Parser.RegisterMathFunctions();
Dictionary<string, double> args = new Dictionary<string, double>();
args["R"] = 100;
JDunkerley.Parser.IComponent comp = JDunkerley.Parser.Parser.GetComponentTree("R*Sin(X/360*2*PI)");
for (int x = 0; x <= 360; x+=5)
{
    args["X"] = x;
    System.Console.WriteLine(x + "\t" + comp.Evaluate((name) => { return args.ContainsKey(name) ? args[name] : double.NaN; }));
}

To Do

  • Add support for Factorial operator
  • Add Test Cases
  • Add support for Indexer
  • Allow functions to decide which parameter to evaluate (i.e. handle if(xx,aa,bb) better)

Last edited Dec 30, 2010 at 4:23 PM by jdunkerley, version 12