# changing numbers to spellings

Paul Rubin http
Wed Oct 4 17:58:49 CEST 2006

```Steve Holden <steve at holdenweb.com> writes:
> You should get some clue about the number conversion (not to menion a
> bunch of code you can lift :) from
>
>      http://www.python.org/pycon/dc2004/papers/42/ex1-C/num2eng.py

For some reason I felt like writing another one, that doesn't use as
much recursion as the last one I posted.  This one is more like
old-fashioned Python and is shorter, but took several refactorings
and was harder to debug:

def spell(n, d=0):
# spell arbitrary integer n, restricted to |n| < 10**66
assert abs(n) < 10**66
if n == 0: return 'zero'
if n < 0:  return 'minus ' + spell(-n, d)

bigtab = ('thousand', 'million', 'billion', 'trillion',
'octillion', 'nonillion', 'decillion', 'undecillion',
'duodecillion', 'tredecillion', 'quattuordecillion',
'octodecillion', 'novemdecillion', 'vigintillion')
smalltab = ('', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen')
out = []
def maybe(cond,s): return (cond and s) or ''

a,n = divmod(n, 1000)
if a:
out.extend((spell(a,d+1), maybe(a % 1000, bigtab[d])))

a,n = divmod(n, 100)
out.append(maybe(a, '%s hundred'% spell(a)))

a,b = divmod(n, 10)
if a > 1:
out.append(('twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety')[a-2] +
maybe(b, '-' + smalltab[b]))
else:
out.append(smalltab[n])
return (' '.join(filter(bool, out)))

# example
print spell(9**69)

```