Number To Word in C++
Read Time:2 Minute, 8 Second
Last Updated on August 17, 2021 by Hammad Rauf
Today after many years of spending my life in the Java world, I decided to revisit the C/C++ land. To my surprise I found out that C++ has made great progress in standardizing the language through the ISO C++ standards process. Anyway, after some initial struggle I finally got this code working.
It is a simple routine, first demonstrated by my teacher and friend in an Oracle Report Writer application for printing bank cheques. I later rewrote it for teaching a C Programming course. Here it is in C++.
(For experimenting with this code yourself, try it on this link for an online compiler http://codepad.org/IvztdjY6 )
#include <string>
#include <stdio.h>
class NumberToWord {
public:
string convert(int numb);
private:
string convertInner(int numb);
string matcher(int digit, int placeValue);
};
string NumberToWord::convert(int numb) {
string words;
if(numb<1000000)
words = convertInner(numb);
return words;
}
string NumberToWord::convertInner(int numb) {
string words = "";
int hund_thousand = 0;
int ten_thousand = 0;
int unit_thousand = 0;
int hundred = 0;
int tens = 0;
int units = 0;
if((numb>=1000) & (numb<1000000)) {
hund_thousand = numb / 100000;
numb -= (hund_thousand*100000);
ten_thousand = numb / 10000;
numb -= (ten_thousand*10000);
unit_thousand = numb / 1000;
numb -= (unit_thousand*1000);
}
if(numb<1000) {
hundred = numb / 100;
numb -= (hundred*100);
tens = numb / 10;
numb -= (tens*10);
units = numb;
}
words += matcher(hund_thousand, 100);
words += " ";
words += matcher(ten_thousand, 10);
words += " ";
words += matcher(unit_thousand, 1);
words += " thousand ";
words += matcher(hundred, 100);
words += " ";
words += matcher(tens, 10);
words += " ";
words += matcher(units, 1);
return words;
}
string NumberToWord::matcher(int digit, int placeValue) {
string result = "none";
if((placeValue == 1) | (placeValue == 100)) {
switch(digit) {
case 1 : result = "one"; break;
case 2 : result = "two"; break;
case 3 : result = "three"; break;
case 4 : result = "four"; break;
case 5 : result = "five"; break;
case 6 : result = "six"; break;
case 7 : result = "seven"; break;
case 8 : result = "eight"; break;
case 9 : result = "nine"; break;
case 0 : result = "";
}
}
if(placeValue == 10) {
switch(digit) {
case 1 : result = "ten"; break;
case 2 : result = "twenty"; break;
case 3 : result = "thirty"; break;
case 4 : result = "forty"; break;
case 5 : result = "fifty"; break;
case 6 : result = "sixty"; break;
case 7 : result = "seventy"; break;
case 8 : result = "eighty"; break;
case 9 : result = "ninety"; break;
case 0 : result = "";
}
}
return result;
}
int main(int argc, char *argv[])
{
int n=27543;
printf("Hello World!\n");
cout << "Number to Convert: " << n << endl;
NumberToWord n1;
cout << "Converted result: " << (n1.convert(n)) << endl;
getchar();
return 0;
}