Friday, August 16, 2013

The str2num function and decimal numbers

There seems to be an issue with the str2num function when what you want is a real value. This matters because it can be used to convert from a string to an int or a real.

In order to successfully convert from a string representation of a decimal value to an actual real type on X++, you can't have any formats on your string. That means that the string has to be representing a double exactly as the real variable does: no thousand separator, and the dot ('.') character for the decimal separator.
It does not consider AX's region when performing the conversion.

Consider the following job:

static void Job1(Args _args)
    str val1, val2, val3, val4;
    real real1, real2, real3, real4;
    val1 = '100,000.000';
    val2 = '100.000,000';
    val3 = '100000,005';
    val4 = '100000.056405';        
    real1 = str2num(val1);
    real2 = str2num(val2);
    real3 = str2num(val3);
    real4 = str2num(val4);

The only valid conversion is the last one, from the variable val4. The real variables have the following values after the assignment:

So just remember to be very careful when converting from a string representing a decimal value to a real X++ type when using the str2num function.

You can always use the .NET Framework instead. If you do, then you'll be able to set a specific culture when converting the double value, like the following valid X++ code:

System.Globalization.CultureInfo cultureInfo = System.Globalization.CultureInfo::CreateSpecificCulture("pt-Br");
    real parsedDouble = System.Double::Parse("1.200,99", cultureInfo);
    print parsedDouble;

No comments:

Post a Comment