Friday, October 9, 2009

How to add leading zeros to a string

When sorting numeric values in an alphanumeric way, you may become unexpected results. Like this

1
11
2

In such cases, it may be helpful to add leading zeros to your string.

And tadaah! Ax to the rescue, again there is a helpful built-in function available, strRFix.
How it works? You specify your value to convert, the desired lenghth of the string and the character to use as a "filler".

Example:

info(strRFix('1',4,'0'));

gives '0001'.
The above numeric values sorted with their alphanumeric counterparts look like this:

0001
0002
0011

Use the function like this:

strRFix(int2str(intvalue),4,'0');

(Replace the intvalue with your variable. )

Basically, you can use this function to right align a string, based on a fixed length.
And don't forget you can specify your own character to 'fix' the string. So dots are allowed, as well as a space.

This function is relatively new in Ax, and even goes without any documentation in the standard help files and on Microsoft's MSDN. Too bad, as unknown is unloved.

Edit:
As someone pointed out in the comments, not so new function at all. After lookin' into it, I found out it's even available in Ax V3 (maybe even earlier?). Lacking good documentation for sure!

2 comments:

  1. That has been in Ax since 2005 at least:)

    http://www.axaptapedia.com/Padding_strings

    But you are right it is very handy!

    ReplyDelete