For example, if you pass 1234, it will return "one thousand two hundred and thirty-four".
The program works for all positive integers up to ten to the power 48, which should be good enough for most practical purposes.
The code is listed below, or you can download it from OneDrive.
def numberConvert( num ):
# pass a string containing a positive integer
# will return the number as a string of words
# for example 1234 will return
# "one thousand two hundred and thirty-four"
number = str(num)
digitlist = []
groupedlist = []
for digit in number:
digitlist.append(digit)
#puts text into grouped list eg
#567893 --> ['893', '567']
while len(digitlist)>0:
s = ""
c = 0
while c<3 and len(digitlist)>0:
s = s + digitlist.pop()
c += 1
groupedlist.append(s[::-1])
out = ""
power = 0
a = ["thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "spetillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quidecillion"]
for item in groupedlist:
if power >0:
out = parseNumber(item) + " "+ a[power-1] + " "+out
else:
out = parseNumber(item)
power += 1
return out
def parseNumber( number ):
#pass a 3 digit string , eg '456'
if len(number) == 1:
return(parseDigit(number))
elif len(number) == 3:
if number[0:1] != '0':
if int(number[1:3]) != 0:
return(parseDigit(number[0:1])+" hundred and "+parseTwoDigit(number[1:3]))
else:
return(parseDigit(number[0:1])+" hundred ")
else:
if int(number[1:3]) != 0:
return("and "+parseTwoDigit(number[1:3]))
else:
return(parseTwoDigit(number[1:3]))
else:
return(parseTwoDigit(number))
def parseDigit( number ):
#deals with one digit numbers
a = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
return a[int(number)]
def parseTwoDigit( number ):
#deals with two digit numbers
a = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
b = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
if (number[0:1]) == '1':
return(b[int(number[1:2])])
elif (number[0:1]) == '0':
return(parseDigit(number[1:]) )
else:
if number[1:] != '0':
return(a[int(number[0:1])-2]+ "-" +parseDigit(number[1:]) )
else:
return(a[int(number[0:1])-2])
#test program
while True:
num = int(input("Enter integer: "))
print(numberConvert(num))