25
Thu, Apr
1 New Articles

Tips and Techniques: Convert Numeric Data in RPG III

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

I've written several articles on how to convert numeric data stored in a character field to a true numeric field. But these articles have always referenced RPG IV as the base language--and for good reason: RPG IV is infinitely easier to program in than RPG III could ever hope to be, and RPG IV's expression support does not implicitly convert character data to numeric.

In RPG III and RPG IV, the MOVE opcode implicitly converts data from character to numeric, so there hasn't been much reason to create a routine that would convert numeric data in a character field into a numeric value; just use the MOVE opcode!

But someone recently asked me how to copy numeric data that is stored in a character field along with some garbage characters into a numeric field. Obviously, they want the garbage to be filtered out.

To do this, you need to perform four basic steps.

  1. Figure out what the garbage characters are.
  2. Remove the garbage characters from the original character field.
  3. Right-justify and zero fill the number within the character field.
  4. Copy it to the target packed or zoned decimal field.

Step 1 is so easy to do that it is purely overlooked. To accomplish this, I set up two named constants as follows:

I              '0123456789.-'        C         NUMS
I              '            '        C         BLKS

The NUMS constant contains all the numeric digits and the minus sign. The BLKS constant is all blanks.

These two fields are then used with an XLATE opcode to remove the good data from the original source value.

In the following example, I translate the numeric digits, the decimal notation symbol, and the minus sign (if applicable) to blanks. The MYFLD field is the original character field that contains both the numeric value and the garbage I want to remove. The field named NONNUM is the target of the XLATE. It receives the garbage data, along with a few blanks.

.....C..n01n02n03Factor1+++OpCodFactor2+++ResultLenDXHiLoEq
     C           NUMS:BLKS XLATEMYFLD     NONNUM

Next, the garbage must be removed from the numeric field. There are two ways of doing this, depending on the format of the original data.

If the original data contains an integer (whole number) that also contains some garbage either before or after the value, we use a combination of the CHEKR (check right) and CHECK (check left) opcodes to isolate the numeric data. Then, we use substring to extract the digits, leaving them left-justified in the character field.

If the original data contains thousands notation (i.e., commas) in addition to the garbage, you use a combination of concatenation and CHECK and CHEKR to accomplish a similar task. I have not implemented this option in this example.

Once the numeric digits are isolated inside the character field and are left-justified, you need to right-adjust the data and zero fill it on the left side. This is extremely easy by using a DO loop and the CAT opcode.

The full, working example is illustrated below and is written in RPG III. I first wrote it in RPG IV simply because my RPG III skills are evaporating with time. But I did use short field names and avoided expressions. In fact, if I were to convert this RPG III source to RPG IV, it would look essentially the same as it did when I originally wrote it.

     H
      **  Convert Character to Numeric in RPG III
      **  To use, set the value of FLDLEN equal to
      **  the length of the character variable that
      **  contains your numeric data. In this example,
      **  I use the MYFLD field to store the text form
      **  of the numeric value. I've initialized it also.
      **  Obviously, in a real-world situation, that 
      **  initial value would not be there, but rather 
      **  it would use your runtime value.
     I              '0123456789-'         C         NUMS
     I              '           '         C         BLKS
      ** The following data structure contains all the
      ** work fields I used in this example. In a real-
      ** world situation, these fields may be declared
      ** in a similar data structure but the MYFLD field
      ** would be replaced with the actual name of the 
      ** character field that contains the numeric data, 
      ** and it would not be part of this data structure.
      ** In addition, the target field, NUMVAL in this
      ** example, would also be a standalone field that
      ** was probably declared elsewhere in the code.
     IFIELDS      DS
     I                                    P   1   30STR
     I                                    P   4   60ENDPOS
     I                                    P   7   90LEN
     I                                    P  10  120CNT
     I                                    P  13  170NUMVAL
     I                                       18  37 NONNUM
     I I            '  2345<>(('             38  47 MYFLD
      ** Be sure to initialize this field to the 
      ** length of your original character field.
      ** That is, the character field that contains
      ** the numeric data. In this example, the
      ** MYFLD field is 10 positions, so we initialize 
      ** the FLDLEN field to 10.
     I I            10                    P  48  500FLDLEN
      **
.....C*Rn01n02n03Factor1+++OpCodFactor2+++ResultLenDXHiLoEq
      ** First, convert all the digits to blanks so that
      ** we end up with the NONNUM field containing only
      ** the crap we want to get rid of.
     C           NUMS:BLKS XLATEMYFLD     NONNUM
      ** Next, find the start and end positions of the
      ** real numeric data in the character field.
     C           NONNUM    CHEKRMYFLD     ENDPOS
     C           NONNUM    CHECKMYFLD     STR   
     C           ENDPOS    SUB  STR       LEN
     C                     ADD  1         LEN
      ** Isolate the digits and the sign (if applicable)
      ** from the original character variable. After this
      ** operation, the MYFLD field should contain only
      ** digits and be left-justified.
     C           LEN       SUBSTMYFLD:STR MYFLD     P
      ** Now, check to see how many positions are on the
      ** right side of the digits. 
     C           ' '       CHEKRMYFLD     ENDPOS
      ** Right-adjust and zero fill the numeric value
      ** in the original character field.
     C           FLDLEN    SUB  ENDPOS    CNT
     C                     DO   CNT
     C           '0'       CAT  MYFLD:0   MYFLD
     C                     ENDDO
      ** At this point, the number has been cleaned up and
      ** may be copied to the packed decimal number properly.
     C                     MOVE MYFLD     NUMVAL
      ** ENDPROC;
     C                     MOVE *ON       *INLR

Bob Cozzi has been programming in RPG since 1978. Since then, he has written many articles and several books, including The Modern RPG Language--the most widely used RPG reference manual in the world. Bob is also a very popular speaker at industry events such as RPG World and is the author of his own Web site and of the RPG ToolKit, an add-on library for RPG IV programmers.

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: