Evaluating a mathematical string formula.

  • Thread starter Thread starter Wade
  • Start date Start date
W

Wade

Hi guys,

I am building a string in code that is a mathematical formula, based on a
lot of criteria specified by the user. Once the formula is complete, I want
to evaluate it to get a result. For example:

dim strFormula as String

strFormula = "((2 + 2) * 3) / 4) - 5"

Once I have this formula, I want to evaluate it and get the result: -2.

Any tips on how I can do this?

Also, is there a way to check if the formula is valid (i.e. I didn't miss
any parenthesis or anything)? I guess I could try to evaluate it, and stick
it in a try - catch block.

Thanks for your time and help!

Wade
 
Three basic options:
1. Write your own postfix/prefix based expressions evaluator
2. Use Reflection.Emit to generate a function to evaluate this formula and
then execute that
3. Use the javascript eval function. There was a example posted in response
to a similar query a week or two back in this group on how to do the exact
same thing.

Rgds,
Anand M
VB.NET MVP
http://www.dotnetindia.com
 
Wade said:
I am building a string in code that is a mathematical formula, based on a
lot of criteria specified by the user. Once the formula is complete, I
want
to evaluate it to get a result. For example:

dim strFormula as String

strFormula = "((2 + 2) * 3) / 4) - 5"

Once I have this formula, I want to evaluate it and get the result: -2.

MathLib
<URL:http://www.palmbytes.de/content/dotnet/mathlib.htm>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top