Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate mathematical expression from a string using VB

Tags:

math

vb.net

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

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

like image 876
Dimitris Sapikas Avatar asked Nov 01 '12 13:11

Dimitris Sapikas


People also ask

How do you check if a string is a mathematical expression?

If you want to check whether an expression(containing variables) is mathematically valid use math. parse(expression) E.g. math. parse('a+b') is valid but math. parse('b+') will throw an exception.


3 Answers

Dim equation As String = "2+6/2"
Dim result = New DataTable().Compute(equation, Nothing)
like image 190
Andrew Avatar answered Oct 14 '22 04:10

Andrew


you can use NCalc for this. It also accepts parameters like x, y, z,...

Dim e As Expression = new Expression("2 + 3 * 5")
Msgbox(17 = e.Evaluate())
like image 21
John Woo Avatar answered Oct 14 '22 05:10

John Woo


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.

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)
like image 26
antony thomas Avatar answered Oct 14 '22 05:10

antony thomas