Is there a method to calculate an equation from a string that looks something like "(1 + 1) * 2"?
Printable View
Is there a method to calculate an equation from a string that looks something like "(1 + 1) * 2"?
Here's a very good article on the algorithm you need:
http://en.wikipedia.org/wiki/Shunting_yard_algorithm
I've heard of that before, it's quite interesting the way it works, but what about implementing error detection? For example a sum such as "3 ** 4".
That's something you'll have to test for as you go along. The algorithm is there to show you how it works.
If I understood your question correct, you want to evaluate a string? Then use
If there is an error in the string it will throw an exeption. You can use regular expressions to check if your string is properly formatted, but that would severly limit the creativity of whoever inputs that string. It's better to catch the exception and show a message (eg. "Cannot compute. Processor overloaded. Self-destruction process initiated").Code:AnswerIS=VAL("(1+1)*2")
Hmm, interesting function, but I tried your example and it's returning 0. I've also tried a less complex sum such as 1 + 1, but that returns 1.
Unless Val has changed drastically since I last looked it will purely convert a string representation of a single number into its numerical equivalent, not evaluate a numerical equation.
You will need to parse the string into 'tokens' and then use one of the standard evaluation algorithms, either shunting yard or reverse polish (do they teach either of these in computer science classes?).
Alternatively, I believe the Windows Scripting Host has an Evaluate function? I could be wrong.
Additionally, DBasnett wrote an 'evaluation' routine: http://www.vbforums.com/showthread.php?t=559071
You are right.
To make up for my lapse, I searched MSDN and came up with this convoluted but effective method - using excel to evaluate your string for you.
http://support.microsoft.com/kb/159974
Well, I found a way, even if it is a bit patchy, it still works.
In my application, I use MSHTML. This solution is ideal for me, but can work for anyone else.
I made a WebBrowser 0px in height, 0px in width. I can make it execute JavaScript from within a Navigate call which evaluates the input and makes the page contents the number returned by the evaluation.
Then when the page has done loading, I get the innerText of the page (IHTMLDocument2), and put it in a variable. Works perfectly!