Advertisement
virtual256

Convert Positive Integers between 0 and 2^31-1 to English words

Jun 4th, 2022 (edited)
1,963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. from typing import List
  2.  
  3. def numberToWords(num: int) -> str:
  4.  
  5. #         Shortcut return if zero:
  6.   if num == 0:
  7.     return "Zero"
  8.  
  9. # Use divmod to parse number into chunks
  10.   chunks = numberSplitter(num, 1000)
  11.  
  12.   ordinals = ['Billion', 'Million', 'Thousand', '']
  13.   words = []
  14.   for chunk in chunks:
  15.     # convert chunk into words, add appropriate ordinal
  16.     words.append(hundredUnitToWords(chunk, ordinals.pop()))
  17.  
  18.   numberWords = ""
  19.   for word in reversed(words):
  20.     if word:
  21.       numberWords += f" {word}"
  22.  
  23.   return numberWords.strip()
  24.  
  25. def hundredUnitToWords(num: int, ordinal: str) -> str:
  26.   hundreds, remainder = divmod(num, 100)
  27.  
  28.   digits = {0: "", 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"}
  29.   tens = {0: "", 2: "Twenty", 3: "Thirty", 4: "Forty", 5: "Fifty", 6: "Sixty", 7: "Seventy", 8: "Eighty", 9: "Ninety"}
  30.   hundred = "Hundred"
  31. #         Compose number within 3 digit block
  32.  
  33.   words = ""
  34.   if hundreds:
  35.     words += f"{digits[hundreds]} {hundred}"
  36.   if remainder:
  37.     # Fix spacing:
  38.     if hundreds:
  39.       words += " "
  40.  
  41.     if remainder < 20:
  42. #               Special case for numbers less than 20 to cover teens
  43.       words += digits[remainder]
  44.     else:
  45.       #  get 10s portion, add units portion
  46.       ten, one = divmod(remainder, 10)
  47.       words += f"{tens[ten]}{'' if (ten == 0 or one == 0) else '-'}{digits[one]}"
  48.   if words:
  49.     words += f" {ordinal}"
  50.  
  51.   return words
  52.  
  53.  
  54. # Splits a positive integer in groups specified by split, returns them in least to most significant order
  55. def numberSplitter(num: int, split: int) -> List[int]:
  56.     splits = []
  57.     while num > 0:
  58.         sub = divmod(num, split)
  59.         splits.append(sub[1])
  60.         num = sub[0]
  61.  
  62.     return splits
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement