ncalc@codeplex – excellent math library


The NCalc codeplex free library is excellent for evaluating mathematical expressions run-time in C#. It has alot of operators, supports functions and parameterized calculations. If you want to define a formula in string format and run-time pass calculated or stored values as parameters, this library is the best free tool I have worked with for a long time.

In my case, the following code gives an idea of the library usage:

string formula = "(2*[A]) + (2 *[B1]) + [B2] + [C]";
var expr = new Expression(formula);
expr.Parameters = new Dictionary<string, object>
    {
        { "A", 100 }, { "B1", 20 }, { "B2", 50 }, { "C", 20 }
    };
Console.WriteLine("Res: '" + formula + "' = " + expr.Evaluate());

The formula has 4 parameters – [A], [B1], [B2], and [C]. The example will use the values stored in the Dictionary. As a result the library will replave the parameters with the values from the dictonary as followed:

(2*100) + (2*20) + 50 + 20 ==> 310

And the result is 310. This is very useful and saves my for a lot of time in the current project at work. The parameters can also be replaced with functions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s