Text input to arithmetic calculation

Got a LiveCode personal license? Are you a beginner, hobbyist or educator that's new to LiveCode? This forum is the place to go for help getting started. Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller

Post Reply
thekillerapp6046
Posts: 5
Joined: Sun Aug 04, 2013 4:13 pm

Text input to arithmetic calculation

Post by thekillerapp6046 » Sun Aug 04, 2013 4:18 pm

Hi livecoders,

If i input to a text field say, "1+2-3/4*5". Can I perform the arithmetics directly and display the answer without manually "processing" the data as a string? Thank you.

Mike.

append[x]
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 17
Joined: Fri Mar 15, 2013 3:12 pm
Contact:

Re: Text input to arithmetic calculation

Post by append[x] » Sun Aug 04, 2013 4:41 pm

Use the value() function:

answer value(fld "myMathFormula")

Andreas
Image

paul_gr
Posts: 319
Joined: Fri Dec 08, 2006 7:38 pm

Re: Text input to arithmetic calculation

Post by paul_gr » Sun Aug 04, 2013 10:40 pm

Allowing the user to enter a mathematical expression from the keyboard can be quite difficult, as you will have to trap accidental input errors.
These input errors will either give an erroneous output or crash the app.

Value(expression) looks like a simple solution, but will not work unless the input is guaranteed to have no mathematic errors.

for example, double operators will not give a true result
value(12++4) will give an execution error.
value(12//3) will give an output of 12.

I would catch input errors using a try catch block; here's a simple example...

on mouseUp
try
answer value(fld "myMathFormula")
catch errorcatch
put " math error in input string"
end try
end mouseUp

I would also limit user input to numbers "0-9", decimal points and the operators "-+/*" if no trig functions like sin,cos,tan etc are required.

cheers
Paul

thekillerapp6046
Posts: 5
Joined: Sun Aug 04, 2013 4:13 pm

Re: Text input to arithmetic calculation

Post by thekillerapp6046 » Tue Aug 06, 2013 8:40 pm

Thanks guys. Paul's tip was very helpful.

Mike

Post Reply