Friday 30 January 2015

AX 2012 - how to evaluate mathematical expressions using code?

Many times its required to evaluate a mathematical expression using the order of execution.
For example, we have a string '((2+3)*4)'. We want to evaluate this expression and return the result.
Such expressions can be validated and evaluated using the X++ class 'XPPCompiler'.




Following is the code snippet:


static void calculateExpression(Args _args)
{
    XppCompiler comp;
   
    str expr;
   
    expr = "(((1+2)*6)/5)";
   
    comp = new XppCompiler();
   
    info(strFmt('%1',comp.compileExpr(expr)));//this validates the expression
   
    info(strFmt('%1',comp.execute(expr)));//this returns the result.
}

AX 2012, X++ expression, BODMAS in AX 2012, validate mathematical expressions, validate formula in AX, formula validation, XPPCompiler, Dynamics AX 2012, Formula calculation, string to mathematical expression, Paranthesis in AX 2012