Search code examples
rpgle

Converting from alpha to numeric with decimals fails


I have to convert a alphanumeric value to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;      

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'


Solution

  • Another way to do get 60.00 is to multiply the result by .01.

    numeric = %dec(alphanumeric:13:0) * .01;
    

    The length and decimal places for %DEC aren't used to specify how to interpret the character value, they are just used to set the size of the result. If the character value is '6000', the result of %DEC is always 6000, but depending on the length and decimals of %DEC, it might be 006000.000, or 6000.00, etc.