How to check if a mathematical equation is valid or not?

In a calculator app,
If a user paste a string in text box and press a button [=]…
How to check if the equation is valid or not?

12+100
Correct

105*(10+5)
Correct

*11-+*10
Incorrect

()10((88)
Incorrect

If Characters other than these are present, then it is invalid equation
blocks (29)

There are two ways to this

  1. Write an elaborate parser that scans each literal, tokenises it, and ensures everything is in order.
    It can be done, but I’m not sure how many blocks you’d need.

  2. Use the evaluate JavaScript block of the WebViewer with the expression as the input. If you get NaN or undefined as an output, you can conclude the expression is invalid.

1 Like

Looks like the second method is easy than the first one
How to do it?

With this block
https://docs.kodular.io/components/layout/views/web-viewer/#evaluate-js

Capture the output with this block:
https://docs.kodular.io/components/layout/views/web-viewer/#after-js-evaluated

1 Like

I know the Evaluate JS blocks…
Should I place the equation string as script
component_method (2)

Yes. But note that special characters like √ won’t work. You’ll have to use Math.sqrt()

Please give a list of valid characters [or its replacements like √ to sqrt()]

Use this extension App Inventor Extensions: Math Parser | Pura Vida Apps

4 Likes

Thank You Very Much
@Vishwas and @Boban

I’m using math extension. facing NaN error when textbox.text having .(dot)
for example :
when textbox.text=1 working
when textbox.text=1. shows NaN
when textbox.text=1.0 working
Blocks:
blocks(2)

Please suggest any solution for this.
Thank you.