The information in this post is based on Dynamics AX 2012 R3. It may or may not be valid for other versions.
Every once in a while, I need to convert a real number to a string. Usually, just passing it to strFmt() is enough, but that function always rounds off to two decimals, which is not always what I want.
Then there’s the num2str() function, which does work well, but requires you know ahead of time how many decimals and characters you want.
What if you just want the number converted to a string, with all digits and decimals? For some reason, this is something that always has me Googling because it is surprisingly obscure to do and I do it so rarely that I usually can’t remember exactly how – in most languages, I would expect that you could just concatenate the real to an empty string, but X++ doesn’t support that.
Anyway, the by far easiest way I have found to do this is by using a .NET call. There are multiple options here as well, with and without options for advanced formatting, but if you just want the really simple conversion of a real to a string, this will suffice:
stringValue = System.Convert::ToString(realValue);
If this code is to be run on the AOS (for example in a batch job), remember to assert the necessary code access permission first. In this case you’ll need an InteropPermission of type ClrInterop to call .NET code, so the full code example would look something like this:
new InteropPermission(InteropKind::ClrInterop).assert(); stringValue = System.Convert::ToString(realValue); CodeAccessPermission::revertAssert();
Be aware that this simple System::Convert function uses the system’s current locale with respect to decimal point character. This may not be an issue for you, but for me who lives in an area where comma is used rather than period as decimal separator, it may require further processing if the string for example needs to be used in a file that must be readable by other systems.