My
Favorite BIF (Built-In Function): %dec
submitted
by Steve
Kontos.
As
of V5R3, the %dec built-in-function was offically put on
steroids. Prior to V5R3 all the function did was convert
non-packed numeric data to packed numeric format. Big deal,
right? Today, this function will handle all kinds of character
to numeric conversions, including date conversions.
Here are
some examples of converting character data to numeric using %dec.
Most of these use the “free form” of RPGLE, but not all.
The %dec bif is equally at-home in either mode.
1) Convert
Character Variable to Numeric Variable
d order
s
9
d order#
s
9p 0
order# =
%dec(order:9:0);
Remember the old days when you had to translate an amount in a flat text file to numeric, and you had to look for the decimal point and add the dollars and cents together? Well, %dec will handle decimal points and negative signs when converting to numeric:
d num1
s
7s 2
num1 =
%dec('-1234.56':7:2);
// num1 = -01234.56
%dec
will NOT handle dollar signs and commas however, but %xlate
can help. For example:
num1 = %dec(%xlate('$,':' ':'$1,234.56'):7:2);
// num1 = 01234.56
%dech
will round (half-adjust) the result:
d num2
s
7p 0
num2 =
%dech('-1234.56':7:0);
// num2 = -0001235
But
wait - as they say on the Ronco commercials - there's more . . .
2) Convert
Character Field to Numeric Key Field
(Note:
there is a field named wcan8 in record WBCUSR)
d cust 8
d custkey ds likerec(wbcusr:*key) inz
c eval custkey.wcan8
= %dec(cust:8:0)
3) Convert
an ISO Date to Character, YYYYMMDD Format, No Dashes
todayISO = %editc(%dec(%date():*ISO ) : 'X');
// Note: %char could have replaced
%editc above, though...
// %char supresses leading zeros.
The 'X' edit will not.
4) Convert a Timestamp to Numeric
d timestamp s
20 0
timestamp =
%dec(%timestamp());
5) Convert Current Date and Time to Numeric Fields
mdt100 = %dec(%date()); // Modified date yyyymmdd 8.0
mtm100 = %dec(%time()); // Modified time hhmmss 6.0
6) Convert Current Date to IBM Julian
d today_jul s
5s 0
today_jul =
%dec(%date():*jul);
7) Convert Current Date to J.D. Edwards Julian
d jde_jul
s
6s 0
jde_jul =
%dec(%date():*jul) + 100000;
8) Convert Current Date to MMDDYY format
d today_mdy s
6s 0
today_mdy =
%dec(%date():*mdy);
That's
it. Using %dec has to be considered the preferred way to
handle character to numeric conversions and date format conversions
in free-format RPG.
Enjoy!