# Math expression parser?

Is there a math expression parser available in either python or java that I can use in FPMI? I’m looking to allow the user to enter a string such as (4*25)+(11/12) and use a parser to calculate the value.

Unfortunately I don’t know of an easy way to accomplish this, but a quick Google search will show you that there are a few out there. Depending on the complexity you need, you might be able to write a small one yourself. A recursive function looking for ()*±/ and numbers shouldn’t be too bad.

If you don’t like that, then you could let our standard python do it for you in an expression. This:`runScript("(0+4)*(13.0/2)")`will return 26, so you can make two DB Tags run this expression for you.

One called ‘Expression’ that’s a string with ‘(0+4)*(13.0/2)’ as it’s value, and one that’s a float with ‘runScript({[.]Expression})’ as it’s value. Now just bind the expression tag to an Input Box on the screen and grab the result from the second tag.

Python is a dynamic scripting language. If you have a user-entered expression, Python will happily run it as python code using the eval function. Arithmetic expressions are valid Python code.

For example, put a Text Field, Button, and Label on a window. Put this code on the button:

[code]textField = event.source.parent.getComponent(“Text Field”)
label = event.source.parent.getComponent(“Label”)

expression = textField.text
result = eval(expression)
label.text = str(result)[/code]

Ta-da!

[color=#FF4000]Obligatory Warning[/color]: You’d better trust the user typing into the text box, because if they’re malicious, they could run any Python code they want, which could be bad.

mathparsers.com has math expression parsers for various languages including java (http://www.mathparsers.com/math-parser-for-java/). bestcode.com has PyMathParser (http://www.bestcode.com/html/evaluate_math_expressions_pyth.html) that uses eval in a safe way by limiting the scope to a pre-defined (or user defined) set of math functions to prevent injection attacks that are otherwise possible with eval function.

Slightly spammy post aside (Resurrecting a two-year thread is a bit of a flag, but mitigated because the python code is free ), bad code could still get in.

I wrote an eval function to add to the app.math script some time ago, but never uploaded it. Lemme see if I can find it…