str2con and leading zeros

If you pack and unpack strings that have leading zero values you are in danger of running into issues because these values might be changed:

static void str2ConLeadingZeros(Args _args)
{
    container con = ['0123', 'OneMoreValue'];
    str s = con2Str(con);
    con = str2con(s);
    info(conPeek(con, 1));
}

This little job shows the issue: The value 0123 is changed to 123 by the str2con call because there’s a type conversion from string to integer. From experience you have leading zero values often in case of customer Ids and suchlike that were migrated from legacy systems. So you really need to be careful with that!

The solution is to simply use str2con_RU (resp. Global::str2con_RU) instead of str2con:

static void str2ConLeadingZeros(Args _args)
{
    container con = ['0123', 'OneMoreValue'];
    str s = con2Str(con);
    con = str2con_RU(s);
    info(conPeek(con, 1));
}

In this case the value 0123 remains.

However I have no idea why this is a function that relates to the Russian internationalization (recognizable by the suffix RU) 🙂

Update:
I was pointed to the fact that str2con has a parameter to avoid the conversion which was overlooked by me in the first place. It’s the third parameter (_convertNumericToInt64 defaulting to true). The second parameter of the method (_sep) allows you to pass the separator string with the default set to a single comma. Of course this might be a source of error, too – you need to make sure that the string you are about to split into single values in the container do not include the separator naturally. In addition to that you have to ensure that the separator is the same when you go back and forth. So an even better solution could look like this:

static void str2ConLeadingZeros(Args _args)
{
    container con = ['0123', 'OneMoreValue', 'Deuss, Volker'];
    str s = con2Str(con, '|');
    con = str2con(s, '|', false);
    info(conPeek(con, 1));
}

Thanks to Pontus for the hint!

2 thoughts on “str2con and leading zeros

  1. Another option it to use the third parameter on str2con, set it to false.

    client server public static container str2con(
    str _value,
    [str _sep,
    boolean _convertNumericToInt64])

Leave a Comment