Link to home
Start Free TrialLog in
Avatar of kak39
kak39

asked on

Calculate a String (Math Formula)

Is it possible to take a string

Example:

Dim answer As String = "150 + 20"

and calculate it to an answer? 170 in a variable? The string would be changing and not always addition, subtration, can sometimes be many variables...

Avatar of fanopoe
fanopoe
Flag of United States of America image

you could parse it into an 2d array (using the spaces as delimiters, based on your example).
Loop back through the array and use a case statement to handle the various operators.
If you are allowing dynamic precedence (9 + 3 * 2 = 15 in dynamic precedence, but = 24 in fixed precedence), you are in for a whole new treat. That is a headache I left behind in CompSci 211 a long time ago.


hth
You could use the Google Web Service API to do this. For example, if you go type 150+34-23 into Google's search box, it will evaluate the expression and return the results.

Therefore, conceptually, you should be able to do this via their web service. Details on how to do that and how to request a license key are here: http://msdn2.microsoft.com/en-us/library/aa289493(vs.71).aspx 

ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Nice tip Idle Mind! I was looking for something like that built into the framework, but came up short.
yeah, wow. I didn't know about that. I spent two weeks building something like that in college ;)
This type of thing is asked for soooo often...I wonder if equivalent capabilities will be added to a future version of the .Net framework?...    =\
Avatar of DineshKammath
DineshKammath

this condition useful only for *,-,+,/ .
What to do for iif(5>0,5,0)
You would need to use the AddCode() method to evaluate actual code...

See: https://www.experts-exchange.com/questions/22437865/Scripting-help.html
And: http://support.microsoft.com/kb/184740