Francisc
Francisc

Reputation: 80505

Eval math formula string with ActionScript

How can I eval Math formulas with AS3? Nothing fancy, things like (10/3)*4+10.

Thanks.

Upvotes: 4

Views: 2743

Answers (3)

Patrick
Patrick

Reputation: 2702

While you could use a huge eval lib like D.eval or AS3Eval, all you really need is something like this simple MathParser (More info about the MathParser)

Here's how you'd use the MathParser:

package {
    import bkde.as3.parsers.*;
    import flash.display.Sprite;
    public class MathTest extends Sprite {
        public function MathTest() {
            var parser:MathParser = new MathParser([]);
            var compiledObj:CompiledObject = parser.doCompile("(10/3)*4+10");
            var answer:Number = parser.doEval(compiledObj.PolishArray, []);

            // EDIT: In case you wanted variables
            var xyParser:MathParser = new MathParser(["x", "y"]);
            var xyCompiledObj:CompiledObject = xyParser.doCompile("(x/3)*y+10");
            var xyAnswer:Number = xyParser.doEval(xyCompiledObj.PolishArray, [10, 4]);
        }

    }

}

Upvotes: 9

jalbee
jalbee

Reputation: 961

If you'd like to avoid using libraries, you could try using the ExternalInterface.call to get access to Javascript's eval function.

For example:

var formula:String = '1+1';
var result:* = ExternalInterface.call('eval', formula);

You may want to check if result == 'undefined' as that would signify an error in the formula syntax.

Upvotes: 1

Tianzhen Lin
Tianzhen Lin

Reputation: 2624

I believe D.eval API is what you are looking for.

Upvotes: 4

Related Questions