converts unsigned long to phrase

PHOTO EMBED

Sat Feb 25 2023 21:46:29 GMT+0000 (Coordinated Universal Time)

Saved by @56phil #c++

// words for digits
// in: unsigned long (ul)   
// out: string &

#include <string>
#include <vector>

typedef unsigned long ul;

std::vector<std::string> const ones{"",     "one", "two",   "three", "four", "five", "six", "seven", "eight", "nine"};
std::vector<std::string> const teens{"ten",     "eleven",  "twelve",    "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    std::vector<std::string> const tens{"",       "",      "twenty", "thirty", "forty",  "fifty", "sixty",  "seventy", "eighty", "ninety"};
   
   std::string wordsForDigits(ul digits) {
    if (digits < 10) {
    return ones[digits];
    } else if (digits < 20) {
    return teens[digits - 10];
    } else if (digits < 100) {
    return tens[digits / 10] +
     ((digits % 10 != 0) ? " " + wordsForDigits(digits % 10) : "");
   } else if (digits < 1'000) {
   return wordsForDigits(digits / 100) + " hundred" +
     ((digits % 100 != 0) ? " " + wordsForDigits(digits % 100) : "");
   } else if (digits < 1'000'000) {
   return wordsForDigits(digits / 1'000) + " thousand" +
   ((digits % 1000 != 0) ? " " + wordsForDigits(digits % 1000) : "");
  } else if (digits < 1'000'000'000) {
  return wordsForDigits(digits / 1'000'000) + " million" +
  ((digits % 1'000'000 != 0) ? " " + wordsForDigits(digits % 1'000'000)
  ▏ : "");
  } else if (digits < 1'000'000'000'000) {
   return wordsForDigits(digits / 1'000'000'000) + " billion" +
   ((digits % 1'000'000'000 != 0)
  ? " " + wordsForDigits(digits % 1'000'000'000)
   : "");
  }
  return "error";
}

void wordsForDigitsHelper(std::string &text, ul digits) {
▏ text = wordsForDigits(digits);
}
content_copyCOPY