02
Sat, Nov
2 New Articles

Clean Up Your Digits!

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

Lately, I've been asked more questions on this topic than on any other: "How do I convert numeric data stored in a character field to a numeric field, when the character field also has some non-numeric elements in it?"

This situation occurs when you have a character field that contains a number as well as other pieces of data--such as edit codes or EDI symbols--or just plain old garbage.

Suppose you just read a record from an EDI transaction or from a Web page. All the data comes into the program in character form. In this case, the data is numeric and is transferred in character format, along with some garbage. Here's an example:

' << 12,345.67 >> (())'

Not very pretty, is it? So how do you convert this value from character to numeric? Or, the question I get all the time: "Is there an easy way to convert character to numeric and remove the garbage from the character field?" The operative word here is "easy." That word does, however, make the answer rather easy: No, there is no easy way to do this.

Filtering Garbage

One of the first things we learn in computer programming classes is the now infamous "garbage in, garbage out" saying. If we have garbage coming into the program, we're probably going to get garbage going out of the program. But why not create a subprocedure that fixes up the data by filtering out the garbage?

To solve this problem, we need to think critically. So let's look at the problem. The data is stored in a character field. Throughout the numeric data, there are non-numeric symbols and embedded blanks. We need to take that value and somehow return only the pure numeric value (with the decimal point, if applicable).

The first thing we need to do is isolate the garbage data. That is, the non-numeric data needs to be removed. In this case, it is the left and right brackets and parentheses, but we really want to do that dynamically (not hard code it), so we need a solution.

The solution I've come up with requires only one line of code to do the isolation and then a few more lines to format the data to be removed.

I've selected the XLATE opcode to do the work for me. It allows us to translate data from one set of characters to another. For example, we could easily convert lowercase letters to uppercase with XLATE.

For our purposes, we need to isolate the garbage data so that we can subsequently remove it. Therefore, what we need to do first is delete the numeric data--that's right, delete the numeric data--so that we have a variable that contains only the garbage we want to remove. Figure 1 illustrates how to accomplish this task.

     D szInData        S             20A   Inz('<<12,345.67>> (())') 
     D                                     Varying 
     D Garbage         S                   Like(szInData
     D CleanVal        S                   Like(szInData
     D SAVEVal         C                   Const('0123456789'
     D SAVEEx          S             10A   Inz('-.') Varying
     D SaveMe          S             30A   Varying
     D Blank           S             30A

     C                   eval      SaveMe = SaveVal + SaveEx
                   
     C                   eval      Garbage = szInData
     C     SaveMe:Blank  XLATE     Garbage       Garbage   

Figure 1: This routine isolates the garbage.

The work field named SAVEME contains the characters we will eventually want to keep. However, since the goal of this step is to isolate the non-numeric data, we need to figure out what characters are present in the original character variable. So we translate the numeric values into blanks, thus leaving only the garbage.

Now that we have the garbage isolated, we need to compress out embedded blanks so that there's not a lot of redundancy in translating blanks into blanks.

If we had the RPG ToolKit available for this example, we would simply use the FINDREPLACE() procedure and be done with it in one statement. However, I have decided to use this opportunity to illustrate the %SCAN and %REPLACE built-in functions and show how you can use them to accomplished the same task, albeit with several more lines of code. Figure 2 illustrates how to compress out the embedded blanks that resulted from the originally isolated garbage text.

C                   eval      nPos = %scan(' ':Garbage)
C                   dow       nPos > 0
C                   eval      Garbage = %Replace('':Garbage:nPos:1)
C                   eval      nPos = %scan(' ':Garbage)
C                   enddo

Figure 2: Compress out embedded blanks.

In Figure 2, we scan the GARBAGE variable for a blank. If a blank is found, the %REPLACE built-in function deletes the embedded blank from the variable. Since GARBAGE is a VARYING field, when we reach the end of the field, 0 is returned from the %SCAN built-in function, and we know it has completed.

A little-known fact about %REPLACE is that if you specify an empty value for the first parameter, you can delete text from within the variable. The position of the text to be deleted is specified on the third parameter, and the number of characters to be deleted is specified on the fourth parameter. An empty value, by the way, is two consecutive apostrophes without any embedded blanks.

Once the compression routine has run, the value of the GARBAGE variable will be as follows:

GARBAGE = ''<<>>(())' 

Note that all the embedded blanks are removed and the garbage characters are up against one another. We now have a clean list of garbage to be removed from our original numeric string. Removing the garbage now becomes a one-line operation, as follows:

C     Garbage:Blank XLate     szInData      CleanVal    

The XLATE opcode is used once again, but this time it removes the garbage from the original character string. Note the fixed-length field named BLANK in Factor 1 of the XLATE operation. I'm using this instead of *BLANKS or ' ' because I want a one-to-one match of the garbage to blanks. I supposed I could have made BLANKS a VARYING field and then set its length to be equal to the length of GARBAGE, as follows:

C                   eval      %len(Blanks) = %len(Garbage)

But I'm not sure that would add any benefit to the task at hand.

Once the XLATE operation has run, the original string, which looked like this...

'<<12,345.67>> (())'

now looks like this:

'   12 345.67      ' 

The next step is to compress the digits together. Fortunately, we just wrote a routine to do that with the garbage data, so we clone that routine and modify it to work with the digits, as illustrated in Figure 3.

C                   eval      nPos = %scan(' ':CleanVal)
C                   dow       nPos > 0
C                   eval      CleanVal= %Replace('':CleanVal:nPos:1)
C                   eval      nPos = %scan(' ':CleanVal)
C                   enddo

Figure 3: Compress out blanks from the numeric value.

The only difference between the routine in Figure 3 and the routine in Figure 2 is the field name on which it is operating. If RPG IV had a macro capability, I would have written a macro to do this task. I could have also created another subprocedure to do the compression, and you might consider doing that for your implementation.

And that's it. The data is now clean. What was once this...
'<<12,345.67>> (())'

is now this:
'12345.67'

If you are on OS/400 V5R2, you can use the %DEC built-in function to convert this value to numeric. If you are on V5R1 or earlier, you would use the CharToNum() procedure in the RPG ToolKit or the MOVE opcode, if applicable.

Figure 4 contains a complete working source member that demonstrates the capability of this routine. It's all wrapped up nicely in a standalone subprocedure named CleanDec().

H OPTION(*SRCSTMTBNDDIR('QC2LE')
 **  (C) 2004 by Robert Cozzi, Jr.
 **  All rights reserved. Permission to use for non-publication
 **  purposes is hereby granted.
 /IF  DEFINED(*CRTRPGMOD)
H NOMAIN
 /ENDIF
 **  Prototype: (cut/paste into a secondary source mbr)
 ** --- CUT HERE --- BEGINNING OF PROTOTYPE
D CleanDec        PR            64A   Varying
D  szInValue                    64A   Const Varying                
D  szKeepMe                     10A   Const Varying OPTIONS(*NOPASS
 ** --- CUT HERE --- END OF PROTOTYPE

 /IF DEFINED(*CRTBNDRPG)
D BadData         S             20A   Inz('<<-12,345.67>> (())')
D GoodData        S             10A
D AmtDue          S              9P 2
     
C                   eval      GoodData CleanDec(BadData)
 /IF DEFINED(*V5R2M0)
C                   eval      AmtDue = %dec(GoodData : 9 : 2)
 /ELSE
 ** NOTE: This statement requires the CHARTONUM procedure
 **       from the RPG ToolKit. If you don't have the ToolKit
 **       (www.rpglib.com) you can use the MOVE opcode instead.
C                   eval      AmtDue = CharToNum(GoodData)
C/ENDIF                   
C                   eval      *INLR = *ON
 /ENDIF

 ** CLEANDEC –  Cleans up a character field that contains
 **             numeric data so that it can be converted
 **             to a real numeric field.
P CleanDec        B                   Export                   
D CleanDec        PI            64A   Varying
D  szInValue                    64A   Const Varying           
D  szKeepMe                     10A   Const Varying OPTIONS(*NOPASS)
     
D nPos            S             10I 0
D Garbage         S                   Like(szInValueInz
D CleanVal        S                   Like(szInValueInz
D SAVEVal         C                   Const('0123456789'
D SAVEEx          S             10A   Inz('-.'Varying
D SaveMe          S             30A   Varying
D Blank           S             30A
       
 **  If the caller passed in different symbols,
 **  use those instead of the default minus and period.
C                   if        %Parms >= 2
C                   eval      SaveEx = szKeepMe
C                   endif
C                   eval      SaveMe = SaveVal + SaveEx
                   
C                   eval      Garbage = szInValue
C     SaveMe:Blank  XLATE     Garbage       Garbage   
C                   eval      nPos = %scan(' ':Garbage)
C                   dow       nPos > 0
C                   eval      Garbage = %Replace('':Garbage:nPos:1)
C                   eval      nPos = %scan(' ':Garbage)
C                   enddo

C                   eval      CleanVal = szInValue
C     Garbage:Blank XLate     CleanVal      CleanVal    
 **  Compress the digits next to each other now that the
 **  garbage has been removed.
C                   eval      nPos = %scan(' ':CleanVal)
C                   dow       nPos > 0
C                   eval      CleanVal= %Replace('':CleanVal:nPos:1)
C                   eval      nPos = %scan(' ':CleanVal)
C                   enddo
C                   return    %Trim(CleanVal)
P CleanDec        E

Figure 4: CLEANDEC cleans up a character field that contains numeric data so that it can be converted to a real numeric field.

To compile the code in Figure 4, use PDM option 14 or 15. Use PDM option 14 when you want to test and demonstrate the subprocedure using something like STRDBG, for example. Use PDM option 15 to create a *MODULE object that could be stored in a service program or bound by copy into your program.

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

$

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: