Converting string formula to mathematical formula

  • Thread starter Thread starter VM
  • Start date Start date
V

VM

If I have a string variable with a formula:

string sMyformula = "3.3*5.2*5";

How can I convert this to a mathematical formula that the compiler can
calculate? For all purposes, the formula in the string will always be valid.

Thanks
 
A quick and dirty solution is to use the JScript engine:

Microsoft.JScript.Vsa.VsaEngine myEngine =
Microsoft.JScript.Vsa.VsaEngine.CreateEngine();

return Microsoft.JScript.Eval.JScriptEvaluate(
"3.3*5.2*5", myEngine
);

See also http://www.odetocode.com/Code/80.aspx for a similar
technique.
 
Thanks.

Would you know if this also evaluates correct formluas with parenthesis (ie.
"(3.3*(5.2*5))+3" ) ?

Thanks again.
 
I suggest you write a postfix / prefix converter, then evaluate using Reverse Polish Notation:

http://www.codeproject.com/csharp/RPN_ExpressionParser.asp

Don't let it scare you -- it is really quite easy,

Regards,

--
Matthew Cosier
Technology Support
Public Sector

Microsoft Australia Pty. Ltd.
*email:[email protected] mob: 0401 932 250 ext:3638


VM said:
Thanks.

Would you know if this also evaluates correct formluas with parenthesis (ie.
"(3.3*(5.2*5))+3" ) ?

Thanks again.
 
Yes, I've tried parens and it works.

--s

Thanks.

Would you know if this also evaluates correct formluas with parenthesis (ie.
"(3.3*(5.2*5))+3" ) ?

Thanks again.
 
I suggest you write a postfix / prefix converter, then evaluate using Reverse
Polish Notation:

http://www.codeproject.com/csharp/RPN_ExpressionParser.asp

Don't let it scare you -- it is really quite easy,

Regards,

Another approach is to use the GoF Interpreter and State patterns to build
your own evaluator. I have articles about them both at http://www.ghytred.com/ShowArticle.aspx?InterpreterPattern
and http://www.ghytred.com/ShowArticle.aspx?StatePattern which builds a
boolean expression interpreter.
 
Back
Top