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, threen is 47, forty-sevenn is 100073, one hundred thousand seventy-threen is 1000000001, one billion onen is 123000000000, one hundred twenty-three billionn is 1474142398007, one trillion four hundred seventy-fourbillion one hundred forty-two million three hundred ninety-eight thousand sevenn is 999999999999999999, nine hundred ninety-nine quadrillionnine hundred ninety-nine trillion nine hundred ninety-ninebillion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-ninen 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 thenumwords
class.numword.cpp
is the implementation file for thenumwords
class.numword-test.cpp
is the application file for testing thenumword
class.
The class itself is about