# changing numbers to spellings

Paul Rubin http
Sun Oct 1 08:37:00 CEST 2006

```"MonkeeSage" <MonkeeSage at gmail.com> writes:
> If you need the actual names for like "Five Hundred and Sixty Seven", I
> think one of the smart people 'round here will have to help with that.
> I have some ideas, but I'm not very good at creating complex
> algorithms.

These kinds of things are generally most easily done with recursion.
================================================================

def spell(n):
# return n spelled out in words
if type(n) not in (int, long):
raise ValueError, n
if n == 0: return 'zero'
return zspell(n)

def zspell(n):
# return n (assumed integer) spelled out in words, with zero = empty string
if n < 0:
return 'minus ' + spell(-n)
elif n == 0:
return ''
elif n < 20:
return ('zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen')[n]
elif n < 100:
a,b = divmod(n, 10)
return '%s%s'% (('twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety')[a-2],
((b > 0) and '-'+zspell(b)) or '')
elif n < 1000:
return '%s hundred %s'% (zspell(n // 100), zspell(n % 100))
elif n < 10**6:
return '%s thousand %s'% (zspell(n // 1000), zspell(n % 1000))
elif n < 10**66:
def xillion(n, d=0):
illions = ('m', 'b', 'tr', 'quadr', 'quint',
'sext', 'sept', 'oct', 'non', 'dec',
'sextemdec', 'septemdec', 'octodec', 'novemdec', 'vigint')
if n == 0: return ''
elif n < 1000:
return '%s %s'% \
(zspell(n),
illions[d] + 'illion')
else:
return '%s %s'% (xillion(n // 1000, d+1),
xillion(n % 1000, d))
return '%s %s' % (xillion(n // 10**6), zspell(n % 10**6))
else:
# I can't count that high!
from math import log10
ch,m = divmod(log10(n), 1.0)
return '%fe%d'% (10.**m, int(ch))

```