Math expression

  • Thread starter Thread starter Rodrigo Ferreira
  • Start date Start date
R

Rodrigo Ferreira

I have a textbox and when i click in ENTER if i have a math expression
inside the textbox, it has to calculate the result.

Supose i have:
123+456+789

My code return well this result,

but if i have 123+456*789 occurrs a problem because first calculates de
123+456 and then 579*789! The code doesn't treat the priorities...

The problem increases with the lenght of the expression....
123+456*45+4/4+4*4536-45 !?!??!

Anyone knows how i can solve my problem? The class Math can help my problem?


Greetings,
Rodrigo Ferreira
 
You have to either teach your expression parser to treat priorities or you
can use the CharpCompiler class to compile the code, execute it and see the
results.
 
CharpCompiler?

cody said:
You have to either teach your expression parser to treat priorities or you
can use the CharpCompiler class to compile the code, execute it and see
the
results.
 
Rodrigo Ferreira said:
I have a textbox and when i click in ENTER if i have a math expression
inside the textbox, it has to calculate the result.

Supose i have:
123+456+789

There are 3-party math-engines out there, but the tend to be expensive for a
reason. What you are trying to do is quite complex.

But you could always cheat and run your expression through MS Excel. Ugly,
but it works just fine. =)

- Michael S
 
Sorry I mean Microsoft.CSharp.Compiler class.
Then you can use Assembly.LoadFrom to load and execute the code.
 
Hi,

IIRC there was a thread about this last week, you have 3 options:
1- Use Reflection Emit to create a new type with the expression you want.
2- Use a third-party expression parser, In the thread I mentioned above were
links to some of them.
3- Implement your parser, for this do a search for reverse polish notation
in google.


I would go first to #2


cheers,
 
And what about Microsoft.CSharp.Compiler class?


Ignacio Machin ( .NET/ C# MVP ) said:
Hi,

IIRC there was a thread about this last week, you have 3 options:
1- Use Reflection Emit to create a new type with the expression you want.
2- Use a third-party expression parser, In the thread I mentioned above were
links to some of them.
3- Implement your parser, for this do a search for reverse polish notation
in google.


I would go first to #2


cheers,
 
Hi,

Yes, you can use it too, but IMO it's included in the 1) . You just want
to evaluate the expression, there is no use to create an assembly with it.
using emit you do a similar thing in memory.
But yes you can create an assembly, load it and call it.

Anyway, I still think that a parser is the best approach, any of the other
techniques will be SUPER slow compared with a parser. It could not be so
difficult I do remember I did one when I was at school :)

cheers,
 
Back
Top