|
|
|
While any Windows user could pop up the Calculator accessory to perform any type of math calculations, it would be great if you could offer him or her the capability to do simple math from within your application. This is a very simple expression evaluator function that does it:
This evaluator is very simple, and has a number of limitations: it does not account for negative numbers nor for parenthesis and sub-expressions, and operands are evaluated from left to right without any priority rule (e.g. "10+2*3" returns 36, and not 16). Nevertheless it is very handy and lets you make you program friendlier to your customer by adding the capability to perform calculation from within a textbox control. This routine shows how to evaluate the expression in a textbox control when the user presses the F2 key: |
Click here to copy the following block | Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer) If KeyCode = vbKeyF2 And Shift = 0 Then Text1.Text = EvalExpression(Text1.Text) Text1.SelStart = Len(Text1.Text) End If End Sub |
If you want to evaluate more complex expressions you can use the MS Script Control library, which offers a simple way to do it. This control has an Eval method that evaluates any expression, with parenthesis, sub-expressions, math functions such as sqr, power, etc., and evaluates the operators in the right order. Add the "Microsoft Script Control" library from the References dialog window, and execute the following code to calculate the result of the given sample expression: |
Click here to copy the following block | Dim oScriptCtl As New ScriptControl Dim sExpr As String oScriptCtl.Language = "VBScript" sExpr = "sqr(25)+2^2+((3+7)/5+1)" MsgBox sExpr & " = " & oScriptCtl.Eval(sExpr) |
Click here to copy the following block | Function EvalExpression(ByVal expression As String) As Double Dim result As Double Dim operand As Double Dim opcode As String Dim index As Integer Dim lastIndex As Integer expression = expression & vbNullChar For index = 1 To Len(expression) + 1 If InStr("+-*/" & vbNullChar, Mid$(expression, index, 1)) Then If lastIndex = 0 Then result = Val(Left$(expression, index - 1)) Else operand = Val(Mid$(expression, lastIndex, index - lastIndex)) Select Case opcode Case "+" result = result + operand Case "-" result = result - operand Case "*" result = result * operand Case "/" result = result / operand End Select End If opcode = Mid$(expression, index, 1) lastIndex = index + 1 End If Next EvalExpression = LTrim$(result) End Function |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|