Str2int and IsInteger

February 4, 2010 at 12:16
filed under Dynamics AX
Tagged ,

Here’s a little ‘be-aware’ I’d like to share.

The function str2int() that converts a string to an integer will return ‘0’ if the input string is not an integer, so it is necessary to check if the string is an integer before casting it.

The function that does this is not IsNumeric() like in SQL or VB, but IsInteger().
Alternatively, you can also use str2IntOk(). Both are found in the global class.

I’ve seen people searching for this method (including me), so I just thought I’d share.

Here’s some sample code:

static void klforStr2intAndIsIntegerTest(Args _args)
    str input_notint    = "abc123";
    str input_int       = "123";
    int ret;
    // be aware, str2int will convert 'non integers' to '0'
    // without warning
    info(strfmt("%1", str2int(input_notint)));
    info(strfmt("%1", str2int(input_int)));
    // you can check if a string is an integer with
    // the isInteger() function from the global class
    // or you the str2IntOk() function
    info(strfmt("%1", isInteger(input_notint)));
    info(strfmt("%1", isInteger(input_int)));
    // check if integer
        // cast to integer
        ret = str2int(input_notint);
        throw error(strfmt("'%1' is not an integer", input_notint));

Update June 2016: if you input “123abd”, the str2int function will return 123, not 0 as you might expect from the “abc123” example!. So be sure to Always use the isInteger function before using str2int.

1 comment

RSS / trackback

  1. Andris

    Thanks :)