Calculate arithmetic problem from text
Is there any simple way,function or dictionary that can solve simple math problem (2 + 5 * 8), and give me result in C#?? But if something like this exist in JavaScript, i am free to use it. Or i need code my own calculator?
Not clear what you want here. You mean processing a string that contains something like (2 + 5 * 8) ?
Yes, get result from text, and that text is simple math problem, like (2 + 5 * 8).
There is an example in the msdn on how to solve simple math calculations with String.Split method here (first example). Perhaps you could code your own based on this.
That wouldn't handle parentheses or any operator priority, would it?
Answer by Pangamini · Jan 18, 2016 at 11:42 AM
You could write your own stack based expression interpreter, which is really not that complicated. You could even make this interpreter to create a .net DynamicMethod by emitting IL code, practially creating a code at runtime, making its execution super fast (provided you want to evaluate the same expression more than once).
Another option would be to use lua interpreter, or another language (for my ingaeme console i internally use Boo compiler, the same language that was recently dropped support for by unity).
But if you want to exercise yourself, trying to write your own stack based expression evaluator is not that much work
Note: CLI language compilers usually emit assemblies, which cannot be unloaded once loaded. This can be an advantage when you call the same expression more times (basically you create and load a DLL at runtime), but if you need to evaluate different string every frame, this will soon fill the memory