13

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

Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
Dimitris Sapikas
  • 622
  • 1
  • 6
  • 22
  • 1
    I think you mean you want to execute it as an *arithmetic* expression. A *regular* expression is [something completely different](http://en.wikipedia.org/wiki/Regular_expression). I am sure you knew that already – MarkJ Nov 01 '12 at 14:10
  • 3
    possible duplicate of [Doing math in vb.net like Eval in javascript](http://stackoverflow.com/questions/1452282/doing-math-in-vb-net-like-eval-in-javascript) – Boann Dec 25 '14 at 00:26
  • Does this answer your question? [How to evaluate a math expression given in string form?](https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form) – duffymo May 10 '23 at 19:09

4 Answers4

23
Dim equation As String = "2+6/2"
Dim result = New DataTable().Compute(equation, Nothing)
Andrew
  • 231
  • 2
  • 3
12

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())
John Woo
  • 258,903
  • 69
  • 498
  • 492
2

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)
  • For mXparser ( http://mathparser.org/ ) there is even nice "hello world" tutorial for VB :-) http://mathparser.org/mxparser-hello-world/mxparser-hello-world-visual-basic/ – Leroy Kegan Apr 21 '17 at 20:51
0

I found this else where, it provides the full functionality of VBScript, and its not an external library.

'Set a reference in your app to "Microsoft Script Control 1.0"
'It is under the COM tab in references, not in the .NET tab
'
Dim SC As New MSScriptControl.ScriptControl With {.Language = "VBSCRIPT"}
Dim Formula As String = "(1+2)*(3+4)"
Try
    Dim Result As Double = Convert.ToDouble(SC.Eval(Formula))
    MessageBox.Show("Math success, " & Formula & " = " & Result.ToString)
Catch ex As Exception
    MessageBox.Show("Not a valid math formula for a double.")
End Try
Fred Kerber
  • 155
  • 3
  • 13