Miklix

Convert a Real to String with All Decimals in Dynamics AX 2012

Published: February 3, 2021 at 5:46:02 PM UTC

In this article, I explain how to convert a floating point number to a string while preserving all decimals in Dynamics AX 2012, including an X++ code example.


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 programming 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.

Share on BlueskyShare on FacebookShare on LinkedInShare on TumblrShare on XShare on LinkedInPin on Pinterest

Mikkel Bang Christensen

About the Author

Mikkel Bang Christensen
Mikkel is the creator and owner of miklix.com. He has over 20 years experience as a professional computer programmer/software developer and is currently employed full-time for a large European IT corporation. When not blogging, he spends his spare time on a vast array of interests, hobbies, and activities, which may to some extent be reflected in the variety of topics covered on this website.