Skip to content

Instantly share code, notes, and snippets.

@bwedding
Last active June 27, 2020 02:15
Show Gist options
  • Save bwedding/7b2bac84a95e471e57de34710d87775b to your computer and use it in GitHub Desktop.
Save bwedding/7b2bac84a95e471e57de34710d87775b to your computer and use it in GitHub Desktop.
Number To Words
#include <map>
#include <string>
#include <vector>
#include <iostream>
#include "ConsoleApplication10.h"
std::map<const int, const std::string> Numbers =
{
{1, "one" }, {2, "two"}, {3, "three"}, {4, "four"}, {5, "five"},
{6, "six"}, {7, "seven"}, {8, "eight"}, {9, "nine"}, {10, "ten"},
{11, "eleven"}, {12, "twelve"}, {13, "thirteen"}, {14, "fourteen"}, {15, "fifteen"},
{16, "sixteen"}, {17, "seventeen"}, {18, "eighteen"}, {19, "nineteen"}, {20, "twenty"},
{30, "thirty"}, {40, "forty"}, {50, "fifty"}, {60, "sixty"}, {70, "seventy"},
{80, "eighty"}, {90, "ninety"}
};
std::string ParseGroup(std::string Val, int group)
{
const std::vector<std::string> vals = { "thousand", "million", "billion" };
std::string retVal;
bool teens = false;
switch (Val.length())
{
case 3:
if (Val[0] != '0')
{
retVal = Numbers[Val[0] - '0'];
retVal += " hundred ";
}
Val.erase(0, 1);
case 2:
if (Val[0] != '0')
{
if (Val[0] == '1')
{
std::string teen = Val.substr(0, 2);
retVal += Numbers[std::stoi(teen)];
teens = true;
retVal += " ";
if (group >= 0)
{
retVal += vals[group];
retVal += " ";
}
return retVal;
}
else
{
retVal += Numbers[(Val[0] - '0') * 10];
}
}
Val.erase(0, 1);
case 1:
if (!teens)
{
retVal += Numbers[Val[0] - '0'];
retVal += " ";
if (group >= 0 && retVal != " ")
{
retVal += vals[group];
retVal += " ";
}
}
}
return retVal;
}
int main()
{
std::string result;
long long int Value = 999888777015;
std::string strVal = std::to_string(Value);
if (strVal.length() > 12)
{
std::cout << "Value is too long. Can't be more than 999,999,999,999\n";
return -1;
}
int groups = (strVal.length() / 3) + (strVal.length() % 3 ? 1 : 0);
int InitLen = 3;
switch (strVal.length() % 3)
{
case 1:
InitLen = 1;
break;
case 2:
InitLen = 2;
break;
}
for (int i = 0, group = 2; i < groups; i++, group--)
{
result += ParseGroup(strVal.substr(0, InitLen), group);
strVal.erase(0, InitLen);
InitLen = 3;
}
std::cout << Value << " in words is:\n" << result << "\n\n\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment