20
Sat, Apr
5 New Articles

RPG Building Blocks: Spelling Numbers

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

Several years ago, we received many requests for a routine to convert a number to words. In response, we published an RPG III program that handled eight-digit numbers of two decimal positions. (See "TechTalk: Numbers-to-Words Conversion Program," MC, May 1994.)

This month, we present an RPG IV service program that contains two nifty subprocedures. The first will spell out any whole number between zero and 4,294,967,295, according to United States conventions. (That is, 10 to the 9th power is called one billion, not one thousand million.) We call it SpellNumber.

The second is a specialized application of SpellNumber, designed for writing amounts of money. We call it SpellCurrency.

If you don't have a routine like this or if you're using an old OPM routine, here's something to add to your ILE toolbox.

This utility consists of two source members. One is a copybook member called NBR01CPY. You can see it in Figure 1. It contains the procedure prototype for subprocedures SpellNumber and SpellCurrency. Any programs or subprograms that use one of these subprocedures should include a /COPY compiler directive for this member.

The second source member, shown in Figure 2, contains the source for service program NBR01SRV. Let's look at this service program and see how it works.

The service program consists of a main section, four subprocedures, and data for the compile- time arrays. The main section declares the global compile-time array variables the subprocedures need and declares the prototypes for the first two subprocedures.

The first two subprocedures-DivideUnsigned and Convert-Units-can be used only within this service program, because they do not include the EXPORT keyword on their procedure definitions. Only the last two subprocedures, SpellNumber and SpellCurrency, may be referred

to by procedures outside this service program. If you want to make the DivideUnsigned or the ConvertUnits subprocedure available to outside procedures, move its prototype into the NBR01CPY source member and add the EXPORT keyword to the subprocedure definition.

DivideUnsigned provides a way to split an unsigned integer into a quotient and remainder of division. I use it to split off the digits and groups of digits for processing. Nothing in this service program will ever divide by zero, but I allowed for that possibility anyway (you never know- I may wind up using this routine somewhere else someday). I chose to return a quotient of zero and a remainder of zero in those cases, rather than set up an error-handling mechanism.

ConvertUnits converts an integer between 1 and 999 to words. Its purpose is to handle each group of three digits. SpellNumber invokes ConvertUnits up to four times, each time passing it another group of three digits, beginning with the rightmost group. As each group of three digits is converted to words, SpellNumber appends the denomination of the group (thousands, millions, etc.) and separates the text description of each group with commas.

SpellCurrency is provided as an easy way to print a dollar amount. It calls SpellNumber twice- once to spell the number of dollars and once to spell the number of cents.

I've included a short test program in Figure 3. In a real application, the UnsNumber and CheckAmount variables would come from a file or be calculated, and the AmountInWords variable would be written to a file. If you run this short test program, use the interactive debugger to see the results, a sample of which are printed for you in Figure 4.

Feel free to modify these subprocedures to fit your needs. For example, SpellNumber returns a string in all uppercase letters. That's probably OK for printing checks, but you may want another case for other applications. I suggest you change the compile-time array data to the case you think you'll need most often. When you need the string to be in some other case, use SpellNumber as an argument to the case conversion functions we presented in the January 1997 "RPG Building Blocks" column.

Also, you may prefer to make SpellCurrency print a numeral, rather than words, for the cents portion of a dollar amount.

Ted Holt is a technical editor with Midrange Computing. You can reach him by email at holt@ midrangecomputing.com.

ILE RPG/400 Reference (SC09-2077, CD-ROM QBJAQE01)

Figure 1: Source member NBR01CPY contains subprocedure prototypes

D SpellNumber pr 128a
D UnsNumber 10u 0 value
D SpellCurrency pr 128a
D CurrencyAmt 9p 2 value *===============================================================

* Spell an unsigned number.
*

* To compile:

Figure 2: Service program NBR01SRV

*

* CRTRPGMOD MODULE(XXX/NBR01SRV) SRCFILE(XXX/QRPGLESRC)
*

* CRTSRVPGM SRVPGM(XXX/NBR01SRV) SRCFILE(XXX/QRPGLESRC) +
* EXPORT(*ALL)

*

*===============================================================

H NoMain

/copy xxx/qrpglesrc,Nbr01Cpy

D DivideUnsigned pr
D Dividend 10u 0 value
D Divisor 10u 0 value
D Quotient 10u 0
D Remainder 10u 0
D ConvertUnits pr 128a
D Units 10u 0 value

D ListOfUnits s 9 dim(19) CTData PerRcd(7)
D ListOfTens s 7 dim( 9) CTData PerRcd(9)
D Group s 8 dim( 4) CTData PerRcd(4)

*===============================================================

* Divide, returning quotient and remainder
*===============================================================

P DivideUnsigned B

Dpi
D Dividend 10u 0 value
D Divisor 10u 0 value
D Quotient 10u 0
D Remainder 10u 0

C if Divisor <> *zero
C Dividend div Divisor Quotient
C mvr Remainder
C else
C eval Quotient = *zero
C eval Remainder = *zero
C endif

PE

*===============================================================

* Convert a number between 1 and 999 to words
*===============================================================

P ConvertUnits B

Dpi 128a
D Units 10u 0 value

D Hundreds s 10u 0
D TensAndOnes s 10u 0
D Tens s 10u 0
D Ones s 10u 0
D WorkString s 128a

C eval WorkString = *blanks
C callp DivideUnsigned (Units: 100:
C Hundreds: TensAndOnes)
C
C if TensAndOnes *zero
C if TensAndOnes <= 19
C eval WorkString = ListOfUnits (TensAndOnes)
C else
C callp DivideUnsigned (TensAndOnes: 10:
C Tens: Ones)

C eval WorkString = ListOfTens (Tens)
C if Ones *zero
C eval WorkString = %trim(WorkString) + '-' +
C ListOfUnits (Ones)

C endif
C endif
C endif
C

C if Hundreds *zero
C eval WorkString = %trim(ListOfUnits (Hundreds))
C +'HUNDRED'+%trim(WorkString)

C endif
C
C Return WorkString

PE

*===============================================================

* Convert a number between 0 and 4,294,967,295 to words
*===============================================================

P SpellNumber B Export

Dpi 128a
D UnsNumber 10u 0 value

D ixs10u 0
D Units s 10u 0
D WorkNumber s 10u 0
D WorkString s 128a
D UnitsString s 128a

C if UnsNumber *zero
C eval WorkString = *blanks
C eval WorkNumber = UnsNumber
C eval ix = 1
C dow WorkNumber *zero
C callp DivideUnsigned (WorkNumber: 1000:
C WorkNumber: Units)
C if Units *zero
C eval UnitsString = %trim(ConvertUnits (Units))
C +''+Group(ix)

C if WorkString = *blanks
C eval WorkString = UnitsString
C else
C eval WorkString = %trim(UnitsString) +
C ','+WorkString
C endif
C endif
C eval ix=ix+1
C enddo
C else
C eval WorkString = 'ZERO'

C endif
C
C return WorkString

PE

*===============================================================

* Convert an amount of currency to words
*===============================================================

P SpellCurrency B Export

Dpi 128a
D CurrencyAmt 9p 2 value

D Dollars s 7p 0
D Cents s 2p 0

C if CurrencyAmt < *zero
C mllzo '0' CurrencyAmt
C endif

C movel CurrencyAmt Dollars
C move CurrencyAmt Cents
C return %trim(SpellNumber(Dollars)) +
C ' DOLLARS AND ' +
C %trim(SpellNumber(Cents)) +
C ' CENTS'

PE

**CTData ListOfUnits
ONE TWO THREE FOUR FIVE SIX SEVEN

EIGHT NINE TEN ELEVEN TWELVE THIRTEEN FOURTEEN
FIFTEEN SIXTEEN SEVENTEENEIGHTEEN NINETEEN
**CTData ListOfTens
TEN TWENTY THIRTY FORTY FIFTY SIXTY SEVENTYEIGHTY NINETY
**CTData Group

THOUSANDMILLION BILLION *===============================================================

* Test the SpellNumber and SpellCurrency functions.
*===============================================================

* To compile:
*

* CRTRPGMOD MODULE(XXX/NBR01TST) SRCFILE(XXX/QRPGLESRC)
*

* CRTPGM PGM(XXX/NBR01TST) BNDSRVPGM(XXX/NBR01SRV)
*

*===============================================================

/copy xxx/qrpglesrc,Nbr01Cpy
D AmountInWords s 128a
D CheckAmt s 9p 2 inz(2408719.57)
D UnsNumber s 10u 0 inz(1788818317)
C eval AmountInWords = SpellNumber(UnsNumber)
C eval AmountInWords = SpellCurrency(CheckAmt)
C eval *inlr = *on TWO MILLION, FOUR HUNDRED EIGHT THOUSAND, SEVEN HUNDRED NINETEEN DOLLARS AND FIFTY-SEVEN CENTS

Figure 3: Use this RPG program to test the SpellNumber
and SpellCurrency functions

Figure 4: Example of the output produced by SpellNumber

TED HOLT

Ted Holt is IT manager of Manufacturing Systems Development for Day-Brite Capri Omega, a manufacturer of lighting fixtures in Tupelo, Mississippi. He has worked in the information processing industry since 1981 and is the author or co-author of seven books. 


MC Press books written by Ted Holt available now on the MC Press Bookstore.

Complete CL: Fifth Edition Complete CL: Fifth Edition
Become a CL guru and fully leverage the abilities of your system.
List Price $79.95

Now On Sale

Complete CL: Sixth Edition Complete CL: Sixth Edition
Now fully updated! Get the master guide to Control Language programming.
List Price $79.95

Now On Sale

IBM i5/iSeries Primer IBM i5/iSeries Primer
Check out the ultimate resource and “must-have” guide for every professional working with the i5/iSeries.
List Price $99.95

Now On Sale

Qshell for iSeries Qshell for iSeries
Check out this Unix-style shell and utilities command interface for OS/400.
List Price $79.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: