How to convert string formula to a mathematical formula in C# [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this questionIf I have a string variable with a formula:
string myformula = "3 * 5 + Pow(2,3)";
How can I convert this string to a mathematical formula that the compiler can calculate?
Finally I got the FLEE library for this purpose. The tool is free and perfectly fit for your purpose. Below is an example how to use this library:
// Define the context of our expression
ExpressionContext context = new ExpressionContext();
// Allow the expression to use all static public methods of System.Math
context.Imports.AddType(typeof(Math));
// Define an int variable
context.Variables["a"] = 100;
// Create a dynamic expression that evaluates to an Object
IDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi");
// Evaluate the expressions
double result = (double)eDynamic.Evaluate();
Not sure why would you mention a compiler, but the simplest way will be to use a math expression evaluator, for example NCalc.
You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)
MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
sc.Language = "VBScript";
string expression = "1 + 2 * 7";
object result = sc.Eval(expression);
MessageBox.Show(result.ToString());
精彩评论