How to convert string "2 + 2" to the value 4 in Visual Basic?
Edward Carson
2007-07-21 19:05:18 UTC
Hello. Am operating in VB6 and am randomly inserting different operators(+,-,*,/,(,)) in my equations to find a sought after answer. But so far have been unable to convert my strings to a value.
Help appreciated.
Five answers:
ebred
2007-07-23 07:38:22 UTC
this will work just fine
..cut and paste the code below and add a button to the form
***********************************************
Private Sub Command1_Click()
Dim ret As Double
ret = calc("/", 8, 2.51234)
Debug.Print (ret)
End Sub
Public Function calc(ByVal op As String, ByVal v1 As String, ByVal v2 As String) As Double
'you want to return a double and calculate with double becuase double values are not rounded. _
Perhaps you would receive the answer you were looking for if you were better at asking questions while being less critical of those attempting to answer your gibberish.
IF you are asking about doing the arithmetic for equations that are input as strings... there is no built-in method for doing that in VB6. You'll have to do it yourself. Shouldn't take you too long unless your requirements go beyond what you've stated above. The first answer gave you a high-level strategy.
Sorry, no one-word answers.
b_dossey
2007-07-22 03:36:04 UTC
HI - my best advice would be to re-evaluate how your input string is formed. If you're using numbers from a user interface, use separate input boxes to capture each value separately. Then, when you're hooking up an event call, convert each value to a relevant datatype (most likely an integer in this case), and apply arithmetic operations to the integers.
Otherwise, you'll have to parse the string and convert to arithmetic datatypes. This can be ugly and is definitely error-prone, so I recommend the first scenario - capture the values from the user interface, convert them to number-friendly formats, and then apply any operations you need.
I hope this helps.
Lisa A
2007-07-22 02:15:09 UTC
You first need to come up with a grammar for your allowable input.
Then write a tokenizer.
Then a parser.
And only finally do you write a state machine to process the numbers and do the actual arithmetic.
E.M.Bed
2007-07-22 08:13:27 UTC
Eval ("2 + 2")
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.