[2005] convert textbox.text to integer
Hi all!
I need to know how to convert a string that contains operators, such as textbox.text = "3+3+3" to a value that can peform this calculation without any parsing or such.
I know I can type this value into the code window and it would perform this calculation.
Thanks.
Re: [2005] convert textbox.text to integer
Can't be done.
You'll have to take it apart and put it back together again using your own logic. Although, this type of thing has been done by other people so maybe you can get a jump start via research.
Re: [2005] convert textbox.text to integer
Well, try this,
Code:
Dim sString As String = "3+5+9-2"
Dim sNotNumbers() As String = {"+", "-", "*", "/"}
Dim iInteger As Integer = 0
Dim sSub As String = ""
Dim sPreviousOperator As String = "+"
Dim bPass As Boolean = False
Dim iTempInteger As Integer = 0
For i As Integer = 0 To sString.Length-1
sSub = sString.Substring(i, 1)
bPass = False
If Array.IndexOf(sNotNumbers, sSub) <> -1 Then 'It's not a number
'Array.IndexOf returns the index of the found item, but -1 if not found
bPass = True
End If
If bPass Then
sPreviousOperator = sSub
Else
If Array.IndexOf(sNotNumbers, sPreviousOperator) = -1 Then
'Hasn't found the last operator, so it must not be a valid operator
Throw New Exception(sPreviousOperator & " is not a valid mathematical operator")
Else
Select Case sPreviousOperator
Case sNotNumbers(0) 'Plus in the array
iInteger += Integer.Parse(sSub)
Case sNotNumbers(1) 'Minus
iInteger -= Integer.Parse(sSub)
Case sNotNumbers(2) 'Times
iInteger *= Integer.Parse(sSub)
Case sNotNumbers(3) 'Divide
iInteger /= Integer.Parse(sSub)
End Select
End If
End If
Next i
I have not tested this or anything, but it should help you somewhat (I think)
Cheers
Re: [2005] convert textbox.text to integer
Hey,
Thanks for the response. Works great. But what if I want to add "2.1+3.1"?
It doesn't like decimals. Any short answer?
Thanks!
Re: [2005] convert textbox.text to integer
change iInteger to dDecimal, and search for the "."
or you could use a string to add up the current values, and parse it to an integer when you find an operator..
IE
Dim sString As String = sSub (in replace of iInteger)
And do Dim dDouble As Double = Double.Parse(sString) in the code underneath sPreviousOperator...
Something like that should work,
Cheers