Math Parser for .NET

For a new software project I’ve searched for a good math parser for .NET.

Beside parsing and evaluating a formula with all common mathematical functions (like sine, cosine, logarithm, …), I additionally needed to be able to use variables inside the formulas.

The best solution that I found is this one here:

The usage is very easy; here you can see a C# example code:

// Instantiate the parser
ExpressionParser parser = new ExpressionParser();

// Create a hashtable to hold values
Hashtable h = new Hashtable();

// Add variables and values to hashtable
h.Add("x", 1.ToString());
h.Add("y", 2.ToString());

// Parse and get the result
double result = parser.Parse("xcos(y)", h);

And for those of you that prefer Visual Basic .NET:

' Instantiate the parser
Dim parser As New ExpressionParser()

' Create a hashtable to hold values
Dim h As New Hashtable()

' Add variables and values to hashtable
h.Add("x", 1.ToString())
h.Add("y", 2.ToString())

' Parse and get the result
Dim result As Double
result = parser.Parse("xcos(y)", h)

It is important that the values are always added as String to the hashtable of variables. The reason is that internally it just injects them into the formula before parsing it – this way they have to be of type String, obviously.

The free assembly is open source and under the LGPL license. Therefore it can also be use in commercial projects as long as it is only linked dynamically as external library.

This post is also available in Deutsch.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>