Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Convert an integer to words
- # e.g 1234 -> One thousand two hundred and thirty four
- def int2words(num):
- w1 = ["", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine "]
- w2 = ["", "teen ", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety "]
- w3 = ["", "ty", "hundred and ", "thousand ", "ty", "hundred and ", "million ", "ty", "hundred and ", "billion ",]
- w4 = ["ten ", "eleven ", "twelve ", "thirteen ", "fourteen ",
- "fifteen ", "sixteen ", "seventeen ", "eighteen", "nineteen"]
- res = ""
- if num >= 9999999999:
- return "Integer is too large"
- snum = str(num)
- i = 0
- while i < len(snum): # iterates left to right
- j = len(snum) - i - 1
- # j counts backwards. j = 1 gets last 2 digits
- a = snum[i] # one character string
- s1 = w1[int(a)] # single digit word
- s2 = w3[j] # order word
- if a == "0" and s2 == "hundred and ":
- s2 = "and "
- if j == 5:
- s2 = ""
- if s2 == "ty":
- s1 = w2[int(a)] # change s1 to xxxty word
- s2 = "" # remove order word
- if (j == 1 or j == 4) and a < "2": # Last 2 digits "00" through "19"
- i += 1
- j -= 1
- y = int(a + snum[i]) # numeric value of last 2 digits
- if y < 10:
- s1 = w1[y] # blank or one through nine
- if y == 0:
- if s2 != "":
- print("**********s2=", s2)
- # s2 = ""
- if res[-5:] == "and ": # Remove "and" if nothing following
- res = res[:-4]
- else:
- s1 = w4[y-10] # ten through nineteen
- s2 = ""
- if j == 3 and y > 0:
- s2 = "thousand "
- res += s1
- res += s2
- i += 1
- if j == 3 or j == 0:
- if res[-5:] == " and ":
- res = res[:-5] # there is nothing following 'and' so remove thw 'and'
- if res == "":
- return("zero")
- return res
- tests = [1008017, 1461234, 502, 61234, 4300, 56, 160, 9999, 1000, 1001, 1100, 0, 6011, 2055,
- 6, 14, 1000017, 1000000, 22000000, 198765432, 2198765432]
- for t in tests:
- print(str(t).ljust(10), int2words(t))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement