First off, thanks. This algorithm is elegant. I would dare say, it qualifies as beautiful code.
I'm not sure if anyone else could use this, but I refactored the English version to suit what we needed. We print monetary amounts that we work with as unsigned integers in all caps.
If anyone else finds it useful, help yourself:
#include "stringstream"
string MonetaryText(unsigned int amount);
void NumToStr(stringstream &buf, unsigned int num);
const char* const NUMBERS_UP_TO_20[] =
{
"", "ONE", "TWO", "THREE", "FOUR",
"FIVE", "SIX", "SEVEN", "EIGHT", "NINE",
"TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN",
"FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
};
const char* const NUMBERS_MULTIPLE_OF_10[] =
{
"TWENTY", "THIRTY", "FORTY", "FIFTY",
"SIXTY", "SEVENTY", "EIGHTY", "NINETY"
};
string MonetaryText(unsigned int amount)
{
stringstream retBuf;
unsigned int cents = amount % 100;
unsigned int dollars = amount / 100;
if(dollars > 0)
{
NumToStr(retBuf, dollars);
retBuf << " DOLLAR";
if(dollars > 1)
retBuf << "S";
}
else
retBuf << "ZERO DOLLARS";
retBuf << " AND";
if(cents > 0)
{
NumToStr(retBuf, cents);
retBuf << " CENT";
if(cents > 1)
retBuf << "S";
}
else
retBuf << " NO CENTS";
return retBuf.str();
}
void NumToStr(stringstream &buf, unsigned int num)
{
if(num < 20)
{
if(buf.tellp() > 0 && num != 0)
buf << " ";
buf << NUMBERS_UP_TO_20[num];
return;
}
unsigned int tmpNum = num / 1000000000;
if(tmpNum > 0)
{
NumToStr(buf, tmpNum);
buf << " BILLION";
num %= 1000000000;
}
tmpNum = num / 1000000;
if(tmpNum > 0)
{
NumToStr(buf, tmpNum);
buf << " MILLION";
num %= 1000000;
}
tmpNum = num / 1000;
if(tmpNum > 0)
{
NumToStr(buf, tmpNum);
buf << " THOUSAND";
num %= 1000;
}
tmpNum = num / 100;
if(tmpNum > 0)
{
NumToStr(buf, tmpNum);
buf << " HUNDRED";
num %= 100;
}
if(num < 20)
NumToStr(buf, num);
else
{
tmpNum = num / 10;
if(tmpNum > 0)
{
if(buf.tellp() > 0)
buf << " ";
buf << NUMBERS_MULTIPLE_OF_10[tmpNum - 2];
num %= 10;
}
tmpNum = num;
if(tmpNum > 0)
NumToStr(buf, tmpNum);
}
}
This statement is false
|