|Using %DEC to Convert Character to Numeric|
Q. In your December 2004 article, "10 Cool Things About RPG IV," I could not get the %XLATE('$*,':' ':Amount) line to work. Testing the %XLATE with constant fields and stepping through it, I found the $ would be replaced by a space, but the asterisk and comma were left in. The only way it would work was to do three %Xlate functions - removing only one of the characters at a time. Did I do something wrong?
A. There was a printing error in that tip. The second %XLATE argument must have as many substitution characters as the search (first) argument specifies. So, there should have been three blanks in the second argument, to match the '$*,' in the first argument.
Here's a corrected and expanded version of the tip:
At Version 5 Release 2, the %DEC function converts a string expression to a packed decimal number, with a specified precision:
Previous releases allowed you to use only numeric expressions with %DEC. When you use the %DEC function to convert a string, the second and third parameters are required.
If the character field Amount has a value of '00123.45' you could convert it to a packed decimal number by coding
If the string value includes non-numeric characters (other than a decimal character), you can include the %XLATE function to translate those characters to blanks. For example, if Amount has a value of '$***12,345.67 ' you could code
%DEC( %XLATE('$*,':' ':Amount) : 7 : 2 )
to first convert the currency symbol, asterisks, and commas to blanks. The %DEC function doesn't mind the embedded blanks, so your program would get a seven digit packed return value of 12345.67 .
If the %DEC function encounters an invalid numeric value, it will return a status code of 105, which you can easily capture:
To round the numeric result, use %DECH. The %INT and %INTH functions also accept string arguments, returning integer values.
Special pricing for the Ashburn area. Book a 5-day onsite class for as little as USD $1300/day. Get a price quote today. Ask for offer VA13.
5-day minimum, special terms apply.