vb.net 使用 VB 计算字符串中的数学表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13178637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Evaluate mathematical expression from a string using VB
提问by Dimitris Sapikas
I want to calculate a arithmetic expression from a string using VB, any ideas ?
我想使用 VB 从字符串计算算术表达式,有什么想法吗?
As an example : "x+2" from a textbox, I want to evaluate the expression
例如:文本框中的“x+2”,我想评估表达式
回答by John Woo
回答by Andrew
Dim equation As String = "2+6/2"
Dim result = New DataTable().Compute(equation, Nothing)
回答by antony thomas
You can use mxparser library for this purpose.Give a reference to mxparser.dll in your project by clicking ADD Reference button of Microsoft Visual Studio.The mxparser library source code or latest dll file can be from www.mathparser.org.The mXparser is a Math Parser for Java, Android, C# .NET (CLS) Libraries.
为此,您可以使用 mxparser 库。通过单击 Microsoft Visual Studio 的“添加引用”按钮,在您的项目中引用 mxparser.dll。mxparser 库源代码或最新的 dll 文件可以来自 www.mathparser.org。mXparser 是适用于 Java、Android、C# .NET (CLS) 库的数学解析器。
Imports org.mariuszgromada.math.mxparser
Private Function evaluate(ByVal str As String) AS Double
Dim expr As Expression = New Expression(str)
DIM d1 As Double
d1=0
d1=expr.calculate()
return d1
End Function
Call to the function can be as follows.
对函数的调用可以如下。
DIM str as String
str=""
str=((45^5)/45))*(5*6)
Dim d as Double
d=0
d=evaluate(str)
MsgBox(" The result of the expression is " + d.ToString)