Evaluate a math expression from a string using VB

I want to compute an arithmetic expression from a string using VB, any ideas?

As an example: "x + 2" from a text field, I want to evaluate the expression

+7
source share
3 answers

You can use NCalc . It also accepts parameters like x, y, z, ...

 Dim e As Expression = new Expression("2 + 3 * 5") Msgbox(17 = e.Evaluate()) 
+9
source
 Dim equation As String = "2+6/2" Dim result = New DataTable().Compute(equation, Nothing) 
+6
source

You can use the mxparser library for this purpose. Send the link to mxparser.dll in your project by clicking the "Add Link" button in Microsoft Visual Studio. The source code for the mxparser library or the latest dll file can be found at www.mathparser.org. MXparser is Math Parser for Java, Android, C # .NET (CLS) libraries.

 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 

A function call may 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) 
+1
source

All Articles