kadghar 1,295
Recognized Expert Top Contributor
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: - sub something_click()
-
textbox2.text=eval(textbox1.text)
-
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: - Public Function Basics(ByVal Str1 As String) As Double
-
Dim i, j, k As Integer
-
Dim Boo1 As Boolean = False
-
Dim mStr1(1), mStr2(0), mStr3(0), mStr4(0) As String
-
Dim mDou1(), mDou2(), mDou3() As Double
-
-
If Str1 = "" Then Return 0 : Exit Function
-
'----------------------------------------------------------'
-
' Save in mStr1 the numbers. Save in mStr2 the operators. '
-
'----------------------------------------------------------'
-
j = 1
-
For i = 1 To Str1.Length
-
k = Asc(Mid(Str1, i, 1))
-
If (k >= Asc("0") And k <= Asc("9")) Or k = Asc(".") Or (k = Asc("-") And Boo1 = False) Then
-
mStr1(j) = mStr1(j) & Chr(k): Boo1 = True
-
ElseIf k = 69 Then
-
mStr1(j) = mStr1(j) & Chr(69) & Mid(Str1, i + 1, 1): i = i + 1
-
Else
-
If Boo1 = True Then
-
ReDim Preserve mStr2(j)
-
mStr2(j) = Chr(k): j = j + 1
-
ReDim Preserve mStr1(j)
-
End If
-
Boo1 = False
-
End If
-
Next
-
'--------------------------------------'
-
' Save in mDou1 the numbers as doubles '
-
'--------------------------------------'
-
ReDim mDou1(UBound(mStr1))
-
For i = 1 To UBound(mStr1): mDou1(i) = CDbl(mStr1(i)): Next
-
'------------------------'
-
' First priority: powers '
-
'------------------------'
-
j = 1: ReDim mDou2(1): mDou2(1) = mDou1(1)
-
For i = 1 To UBound(mStr2)
-
If mStr2(i) = "^" Then: mDou2(j) = mDou2(j) ^ mDou1(i + 1)
-
Else
-
ReDim Preserve mStr3(j): mStr3(j) = mStr2(i)
-
j = j + 1: ReDim Preserve mDou2(j)
-
mDou2(j) = mDou1(i + 1)
-
End If
-
Next
-
If UBound(mStr3) = 0 Then Return mDou2(1) : Exit Function
-
'-----------------------------------------'
-
' Second priority: products and quotients '
-
'-----------------------------------------'
-
j = 1: ReDim mDou3(1): mDou3(1) = mDou2(1)
-
For i = 1 To UBound(mStr3)
-
If mStr3(i) = "*" Then: mDou3(j) = mDou3(j) * mDou2(i + 1)
-
ElseIf mStr3(i) = "/" Then: mDou3(j) = mDou3(j) / mDou2(i + 1)
-
Else
-
ReDim Preserve mStr4(j): mStr4(j) = mStr3(i)
-
j = j + 1: ReDim Preserve mDou3(j)
-
mDou3(j) = mDou2(i + 1)
-
End If
-
Next
-
If UBound(mStr4) = 0 Then Return mDou3(1) : Exit Function
-
'---------------------------------------'
-
' Third priority: sums and differences. '
-
'---------------------------------------'
-
Basics = mDou3(1)
-
For i = 1 To UBound(mStr4)
-
If mStr4(i) = "+" Then: Basics = Basics + mDou3(i + 1)
-
ElseIf mStr4(i) = "-" Then: Basics = Basics - mDou3(i + 1): End If
-
Next
-
End Function
and for the parenthesis handler: - Public Function Eval(ByVal Str1 As String) As Double
-
Dim i, j, k(2), c As Integer
-
Dim Str2 As String
-
If Str1 = "" Then Return 0 : Exit Function
-
'------------------------------'
-
' Find the outern parenthesis. '
-
'------------------------------'
-
j = 0
-
For i = 1 To Str1.Length
-
If Mid(Str1, i, 1) = "(" Then
-
If j = 0 Then k(1) = i
-
j = j + 1
-
ElseIf Mid(Str1, i, 1) = ")" Then
-
If j = 1 Then: k(2) = i: Exit For: End If
-
j = j - 1
-
End If
-
Next
-
'----------------------------------------------------------------------'
-
' Using recursivity, it'll find the inner ones, and add '*' when needed'
-
'----------------------------------------------------------------------'
-
If j = 1 Then
-
If k(1) > 1 Then c = Asc(Mid(Str1, k(1) - 1, 1))
-
Str2 = ""
-
If (c >= Asc("0") And c <= Asc("9")) Or c = Asc(".") Then Str2 = "*"
-
If c = Asc("-") Then Str2 = "1*"
-
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
-
End If
-
Return basics(Str1)
-
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
2 12296
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.SetE xpression("x+si n(x)");
MathParser.SetX (3);
MathParser.SetY (2);
double value = MathParser.getV alueAsDouble();
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Tonino |
last post by:
Hi,
I have a task of evaluating a complex series (sorta) of mathematical
expressions and getting an answer ...
I have looked at the numarray (not really suited??) and pythonica (too
simple??) and even tried using eval() ... but wondered if there were
other packages/modules that would enable me to to this a bit easier...
The formula/equations are for investment calculations (Swap Yields).
|
by: mojo |
last post by:
Is there a nice way to have HTML display mathematical expressions
that contain radical symbols (square root, cube root, ..., nth root)
that look nice.
The best I can come up with is by having a table, a CSS border, the
radical sign:
<TABLE>
<TR>
<TD>&radic</TD><TD style="border-top: 1pt solid black;">103</TD>
</TR>
|
by: Zeng |
last post by:
Hello,
Please help!!! I've been stuck on this issue for months. I just wonder if
there is a way to programmatically evaluate expression
strings such as
( ( 3 + 5 ) / 2 ) > 4 --> this should return 0 or false( ( 3 + 6 ) / 3 ) >
( ( 5 + 3 ) / 4 ) --> this should return 1 or trueThanks for any comment or
|
by: EDom |
last post by:
Hi,
I have expressions in a string like "100/24*5" and so on. How can I evaluate
this expression to get the result.
Regards,
Vineet
|
by: Ray Martin |
last post by:
I have created a custom datagridcolumn, and would like to color the cell
based on criteria passed as a parm when the column is created. I would like
this to be generic so I want to do something similar to the Clipper/dBase
function "&", or even the DOTNET Debug.Evaluate methid.
So, for example if I wanted the cell in row 5 to be the one to be colored
differently I could do something like:
mynewcolumn = new...
| |
by: jsta43catrocks |
last post by:
In C++, my "switch" statement is okay when I ask it do evaluate ONE expression. (My number that I'm evaluating is one of ten single digits; I have ten cases for the ten digits.)
BUT, I have five separate digits to evaluate.
I can't believe that the only solution is to do:
switch (num1)
{
case 0:...
case 9:
|
by: mstorkamp |
last post by:
I need to evaluate simple arithmetic expressions.
I wrote a quick and dirty program that allows me to enter dimensions
off of a drawing, and based on global or local tolerances calculate an
upper and lower limit to put in an inspection worksheet.
When it asks for a dimension I would like to be able to type in
something like: '(12.5+10)/2' or '150-3.45'
What I'm looking for is a function along the lines of 'double
|
by: jtanz0 |
last post by:
Im fairly new to java programming although i have some experience in python.
I have to create a calculator program (command line) which takes as input a mathematical expression consisting of decimal numbers and the four basic mathematical operators (+,-,/,*) and correctly handles nested mathematical expressions.
Some examples:
• 5 + 6 * 2 results in 17
• (5 + 4) * (4 - 2) results in 18
i can do the basics ie taking an input and...
|
by: serave |
last post by:
How do i evaulate a mathematical expression that is entered in a text
field.
Ex:
Text Fields:
Xo=23
X1= 250
Expression: y = Xoe^(x1+Xo)-cos(X0+X1)+23Xo
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |