...

/

Convert Numbers to Words

Convert Numbers to Words

Learn to convert numbers to words.

We'll cover the following...

When learning a new language, it can be helpful to work on a project that exposes the nuances of the language. The numwords class is an excellent exercise for this purpose.

The numwords is a class that spells out a number in words. It can be useful for banking and accounting applications. It looks like this in use:

int main() {
bw::numword nw{};
uint64_t n;
nw = 3; bw::print("n is {}, {}\n", nw.getnum(), nw);
nw = 47; bw::print("n is {}, {}\n", nw.getnum(), nw);
n = 100073; bw::print("n is {}, {}\n", n, bw::numword{n});
n = 1000000001; bw::print("n is {}, {}\n", n, bw::numword{n});
n = 123000000000; bw::print("n is {}, {}\n", n, bw::numword{n});
n = 1474142398007; bw::print("n is {}, {}\n", n, nw.words(n));
n = 999999999999999999; bw::print("n is {}, {}\n", n, nw.words(n));
n = 1000000000000000000; bw::print("n is {}, {}\n", n,nw.words(n));
}

Output:

n is 3, three
n is 47, forty-seven
n is 100073, one hundred thousand seventy-three
n is 1000000001, one billion one
n is 123000000000, one hundred twenty-three billion
n is 1474142398007, one trillion four hundred seventy-four
billion one hundred forty-two million three hundred ninety-
eight thousand seven
n is 999999999999999999, nine hundred ninety-nine quadrillion
nine hundred ninety-nine trillion nine hundred ninety-nine
billion nine hundred ninety-nine million nine hundred ninety-
nine thousand nine hundred ninety-nine
n is 1000000000000000000, error

How to do it

This recipe originated as an exercise in creating production-ready code. For that reason, it's in three different files:

  • numword.h is the header/interface file for the numwords class.

  • numword.cpp is the implementation file for the numwords class.

  • numword-test.cpp is the application file for testing the numword class.

The class itself is about 180180 lines of code, so we'll just cover the ...