468,556 Members | 2,051 Online

# Evaluate mathematical expressions with VB 1,295 Expert 1GB
Many people asks if there is a way to write a mathematical expression, writen as a string in a text box, so they can do something like:

Expand|Select|Wrap|Line Numbers
1. sub something_click()
2.     textbox2.text=eval(textbox1.text)
3. end sub
Well, of course it's posible, and can be done with some characters mannaging. This way you can complicate it as much as you want. The way i usualy do it is in 5 simple steps:

1. Create 2 string arrays, and save numbers in one and operators in the other one:
2. Transform the first array into a doubles array (so you can work using Option Strict)
3. Evaluate powers (i dont evaluate roots, since you can use a^0.5 instead of sqrt, etc...)
4. Evaluate products and divisions.
5. Evaluate sum and difference.

After this little function is done, i like to make another function to handle parenthesis, using some recursivity, this is very useful while working with roots, since you can write a^(1/5) instead of the 5th root.

Lets call the first function 'Basics', and lets call the parenthesis handler 'Eval', and they could look like this:

Expand|Select|Wrap|Line Numbers
1. Public Function Basics(ByVal Str1 As String) As Double
2.         Dim i, j, k As Integer
3.         Dim Boo1 As Boolean = False
4.         Dim mStr1(1), mStr2(0), mStr3(0), mStr4(0) As String
5.         Dim mDou1(), mDou2(), mDou3() As Double
6.
7.         If Str1 = "" Then Return 0 : Exit Function
8.         '----------------------------------------------------------'
9.         ' Save in mStr1 the numbers. Save in mStr2 the operators.  '
10.         '----------------------------------------------------------'
11.         j = 1
12.         For i = 1 To Str1.Length
13.             k = Asc(Mid(Str1, i, 1))
14.             If (k >= Asc("0") And k <= Asc("9")) Or k = Asc(".") Or (k = Asc("-") And Boo1 = False) Then
15.                 mStr1(j) = mStr1(j) & Chr(k): Boo1 = True
16.             ElseIf k = 69 Then
17.                 mStr1(j) = mStr1(j) & Chr(69) & Mid(Str1, i + 1, 1): i = i + 1
18.             Else
19.                 If Boo1 = True Then
20.                     ReDim Preserve mStr2(j)
21.                     mStr2(j) = Chr(k): j = j + 1
22.                     ReDim Preserve mStr1(j)
23.                 End If
24.                 Boo1 = False
25.             End If
26.         Next
27.         '--------------------------------------'
28.         ' Save in mDou1 the numbers as doubles '
29.         '--------------------------------------'
30.         ReDim mDou1(UBound(mStr1))
31.         For i = 1 To UBound(mStr1): mDou1(i) = CDbl(mStr1(i)): Next
32.         '------------------------'
33.         ' First priority: powers '
34.         '------------------------'
35.         j = 1: ReDim mDou2(1): mDou2(1) = mDou1(1)
36.         For i = 1 To UBound(mStr2)
37.             If mStr2(i) = "^" Then: mDou2(j) = mDou2(j) ^ mDou1(i + 1)
38.             Else
39.                 ReDim Preserve mStr3(j): mStr3(j) = mStr2(i)
40.                 j = j + 1: ReDim Preserve mDou2(j)
41.                 mDou2(j) = mDou1(i + 1)
42.             End If
43.         Next
44.         If UBound(mStr3) = 0 Then Return mDou2(1) : Exit Function
45.         '-----------------------------------------'
46.         ' Second priority: products and quotients '
47.         '-----------------------------------------'
48.         j = 1: ReDim mDou3(1): mDou3(1) = mDou2(1)
49.         For i = 1 To UBound(mStr3)
50.             If mStr3(i) = "*" Then: mDou3(j) = mDou3(j) * mDou2(i + 1)
51.             ElseIf mStr3(i) = "/" Then: mDou3(j) = mDou3(j) / mDou2(i + 1)
52.             Else
53.                 ReDim Preserve mStr4(j): mStr4(j) = mStr3(i)
54.                 j = j + 1: ReDim Preserve mDou3(j)
55.                 mDou3(j) = mDou2(i + 1)
56.             End If
57.         Next
58.         If UBound(mStr4) = 0 Then Return mDou3(1) : Exit Function
59.         '---------------------------------------'
60.         ' Third priority: sums and differences. '
61.         '---------------------------------------'
62.         Basics = mDou3(1)
63.         For i = 1 To UBound(mStr4)
64.             If mStr4(i) = "+" Then: Basics = Basics + mDou3(i + 1)
65.             ElseIf mStr4(i) = "-" Then: Basics = Basics - mDou3(i + 1): End If
66.         Next
67. End Function
and for the parenthesis handler:

Expand|Select|Wrap|Line Numbers
1. Public Function Eval(ByVal Str1 As String) As Double
2.         Dim i, j, k(2), c As Integer
3.         Dim Str2 As String
4.         If Str1 = "" Then Return 0 : Exit Function
5.         '------------------------------'
6.         ' Find the outern parenthesis. '
7.         '------------------------------'
8.         j = 0
9.         For i = 1 To Str1.Length
10.             If Mid(Str1, i, 1) = "(" Then
11.                 If j = 0 Then k(1) = i
12.                 j = j + 1
13.             ElseIf Mid(Str1, i, 1) = ")" Then
14.                 If j = 1 Then: k(2) = i: Exit For: End If
15.                 j = j - 1
16.             End If
17.         Next
18.         '----------------------------------------------------------------------'
19.         ' Using recursivity, it'll find the inner ones, and add '*' when needed'
20.         '----------------------------------------------------------------------'
21.         If j = 1 Then
22.             If k(1) > 1 Then c = Asc(Mid(Str1, k(1) - 1, 1))
23.             Str2 = ""
24.             If (c >= Asc("0") And c <= Asc("9")) Or c = Asc(".") Then Str2 = "*"
25.             If c = Asc("-") Then Str2 = "1*"
26.             Str1 = Eval(Mid(Str1, 1, k(1) - 1) & Str2 & Eval(Mid(Str1, k(1) + 1, k(2) - k(1) - 1)).tostring & Mid(Str1, k(2) + 1).tostring).tostring
27.         End If
28.         Return basics(Str1)
29. End Function
It's a function made for VB 2005 Express edition, syntaxis may change in other versions of VB, so you may have to change some 'Returns' 'ToString' and '.Length', and the way you declare the arrays or handle the lines using ':'.

You should also note that it will add a '*' when a parenthesis needs it before, but it won't when it needs it after. so 2(8) = 16 but (2)8 will be an error.

It's quite a simple function, but im sure you can find it useful.

Kad
Jan 14 '08 #1
2 10926 Hesperos
1 wow
it's very good.
Mar 22 '08 #2
MeteVeli
1 Bestcode.com has mathematical expression parsers for many languages.

http://www.bestcode.com/html/mathparser.html

bcParser.NET Math parser is implemented in C#. It allowes the programmer set the expression as a string, create user defined variables, set their values, create user defined functions and get expression value with one function call. The expression can contain arithmetic operators, logical operators, variables, functions, numeric and string literals.

A simple example looks like this:
MathParser.SetExpression("x+sin(x)");
MathParser.SetX(3);
MathParser.SetY(2);
double value = MathParser.getValueAsDouble();

The programmer can implement his own functions in any .NET language and hook them up to the Math Parser object so that they can be used in expressions all with few lines of code.

bcParser.NET math parser is a well tested, easy to use, simple .NET Class that can save time and money for experienced or novice programmers alike. It comes with C# soure code so you are never stuck with a black box.

There is also a bcParserX COM component to evaluate formulas given as strings. It can be used in VB.NET as well as other COM capable languages.
Aug 7 '10 #3

### Post your reply

Sign in to post your reply or Sign up for a free account.

### Similar topics

 8 posts views Thread by Tonino | last post: by 5 posts views Thread by mojo | last post: by 13 posts views Thread by Zeng | last post: by 2 posts views Thread by EDom | last post: by 2 posts views Thread by Ray Martin | last post: by 13 posts views Thread by jsta43catrocks | last post: by 6 posts views Thread by mstorkamp | last post: by 2 posts views Thread by jtanz0 | last post: by 14 posts views Thread by serave | last post: by reply views Thread by ravipankaj | last post: by reply views Thread by NPC403 | last post: by 7 posts views Thread by isladogs | last post: by reply views Thread by captainhaddock | last post: by 3 posts views Thread by hwsilver | last post: by 3 posts views Thread by laxmi96 | last post: by 1 post views Thread by rupashini | last post: by 1 post views Thread by UniDue | last post: by reply views Thread by PrototypeChain | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.