tags:

views:

74

answers:

4

Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?

I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.

If it makes any differences, I am using .NET 4.0

Thanks for any input or direction.

+2  A: 

You can try using DataTable.Compute.

A related one is DataColumn.Expression.

Also check out: http://stackoverflow.com/questions/1452282/doing-math-in-vb-net-like-eval-in-javascript

Note: I haven't used these myself.

Moron
Since I was not doing any trig calculations (just simple math), the DataTable.Compute option was the easiest to implement.
Brandon
A: 

Another option you may want to look into is the Spring.NET Framework's expression evaluation functionality. It can do a lot more than math, too.

However, the entire Spring.NET Framework might be a bit of overkill for your needs if you don't require the rest of the functionality.

Joshua Rodgers
A: 

Related: Equation expression parser with precedence.

Jared Updike
A: 

I urge caution against choosing an existing generic expression evaluator over a purpose-built math evaluator. The reason for this is that the expression evaluators are not limited to just math. A clever individual could use this to create an instance of any type in the framework and call any method on the type, and that would allow him to do some decidedly unwelcome things. For example: new System.Net.WebClient().DownloadFile("illegalchildpornurl", "C:\openme.gif") will evaluate just fine in most of those, and do just what you'd expect it to.

This doesn't mean don't look for something that's already written. It just means be careful. You want one that does math, and only math. Most of what's already out there isn't that picky.

Joel Coehoorn