Text Based Basic Formula Calculator Function/Class

2019-08-19 00:23发布

Looking for something like

int Result; 
DataTable dt2 = new DataTable();
var v = dt2.Compute("3+2-34*12", "");
Result=Convert.ToInt32(v);

the code above, which solves the text base formula. Unfortunately, the code above only works for some basic operators (+,-,/,*). Need a little more complex one (like squareroot, ^ at least).

Could you help me to find something tosolve for a little more complex equations?

1条回答
别忘想泡老子
2楼-- · 2019-08-19 00:48

You can use Roslyn scripting API for that. Add Microsoft.CodeAnalysis.CSharp.Scripting package and evaluate C# code like this:

static async Task<double> EvaluateFormulaAsync(string formula)
{
    return await CSharpScript.EvaluateAsync<double>(formula,
        ScriptOptions.Default.WithImports("System.Math"));
}

Usage:

var result = EvaluateFormulaAsync("Sqrt(2) + 2 * 15").Result; // 31.4142135623731

Note: Scripting API requires .NET Framework 4.6+ or .NET Core 1.1

查看更多
登录 后发表回答