Converting string to mathematicalexpression

R

Ron Bullman

Jonas,

You have at least three alternatives to proceed:
A) Create your own parser to parse the expressions to some intermediate
representation and then compile and execute (or interpret) that. (keywords
for google, recursive descent parser, abstract stack machine).
B) If the expressions are valid C# (VB) you could utilize the inbuild
features of .NET. Create CodeDom compile unit from the expression, compile
it to assembly and execute that. (namespaces to study System,
System.CodeDom, System.CodeDom.Compiler, System.Reflection).
C) Incorporate scripting capabilities to your application via VSA (Visual
Studio for Applications). (namespace to study Microsoft.Vsa and newsgroup
....dotnet.vsa).

You might wanna specify more detailed manner your requirements inorder to
have better advice which route to take.


Ron
 
J

Jonas Prismesen

Hi!

I have string like this:
string expr = "123/(12*3)";

And I want to actually calculate the mathematical
expression in the string. Is there an easy way do it? Or
do I have to extract all the parts from the string, which
will be difficult since the expression will change in my
app..

I'm using VS.NET 2003 and c#.

In advance thank you!
 
R

Ron Bullman

Jonas,

Comments inline.

Ron
Jonas Prismesen said:
Thanks for your reply Ron!

What I want to do in my app is have a textbox where the
user can enter formulas with a variable (eg. y) like
this: y/122 or (y*34)-12+(2*y)

Then the user will be able to enter enter a value in
another textbox which will replace the y in all the
formulas.

It seems that you only need to have a simple expression evaluator. Most
probably someone has implemented it already. Try to google. However if you
can't find any such you still might want implement your own one.
I managed the replacing by simply using the replace-
method of string. With y=12 this gives me the two
string: "12/122" and "(12*34)-12+(2*y)"

Now the problem is calculating the expressions. I think
creating a parser would be quite complex as the
expressions can be very different..

Quite the opposite parsing simple mathematical expressions is pretty
straightforward. The key thing is to have a grammar and use recursive
descent parser. Don't reinvent the wheel here ;-), there are lot of examples
how to implement it straightforward manner. (for example
http://pages.cpsc.ucalgary.ca/~gilesb/ta.2003/411/calc/calculator.pdf and
plenty of similar ones).
 

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

Top