Thursday, June 23, 2016

One of those functions...

Now and then you come across AX functions you haven't heard about or that you have never really used. The lack of usage is often linked to the lack of documentation, but that's another story.

Today I came across the formattedStr2Num function. It is able to take a formatted string with some arithmetic and do a calculation of the expression. Something I have often seen developers write code to pass through the compiler and run the compiled code to do.

Here is a small example of how to use it:

static void formattedStr2NumDemo(Args _args)
    str s = "(8 + 2) / 2 * 4";
    info(strFmt("%1", formattedStr2num(s)));

The function actually also pass the expression through the compiler, but in a controlled way so you can't just run any old arbitrary (dangerous) code through it.

If you combine this with a dynamic strFmt call, you have yourself a small expression calculation engine.

The timing for me to figure this out is awful, since the function is deprecated in AX 7. From AX 7 you could instead use something like ADO.NET's expressions parser in DataTable.Compute.

Thanks to Marco Scotoni, Johan van Veldhuizen and of course Peter Villadsen for being smarter than me and learning me this today through the Yammer group we share membership of. And I hope I wasn't the last AX developer on earth to learn about this function.


Moutasem al-awa said...

Good share and good to know. Almost laughed when you said it's deprecated though :D

Palle Agermark said...

Yeah, that's a sad story :-)

Nandakishore Varre said...

Hi Palle Agermark, First of all thank you for sharing your knowledge. It would be a great help, if you can provide a code snippet/ Yammer links which shows "how to use it in AX7". Thanks in advance.

Nanda Kishore V