Welcome, guest | Sign In | My Account | Store | Cart

Converts numbers in to their english equivelents. It can spell out any integer between -999999999999999 and 999999999999999, inclusive.

Python, 51 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def getNum(n):
    nums = ['zero','one','two','three','four','five','six','seven','eight','nine','ten', \
    'eleven','twelve','thriteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
    tens = [None, None,'twenty','thrity','fourty','fifty','sixty','seventy','eighty','ninety']
    try: n = int(n)
    except ValueError: return 'NaN'
    
    if n < 0:
        return 'negitive ' + getNum(abs(n))
    if n < 20: 
        return nums[n]
    if n < 100: # and n >= 20
        s = tens[n//10]
        if n % 10:
            s += ' ' + nums[n%10]
        return s
    if n < 1000: # and n >= 100
        s = nums[n//100] + ' hundred'
        if n % 100:
            s += ' ' + getNum(n - (n//100)*100)
        return s
    if n < 1000000: # and n >= 1000
        s = getNum(n//1000) + ' thousand'
        if n % 1000:
            s += ' ' + getNum(n - (n//1000)*1000)
        return s
    if n < 1000000000: # and n >= 1000000
        s = getNum(n//1000000) + ' million'
        if n % 1000000:
            s += ' ' + getNum(n - (n//1000000)*1000000)
        return s
    if n < 1000000000000: # and n >= 1000000000
        s = getNum(n//1000000000) + ' billion'
        if n % 1000000000:
            s += ' ' + getNum(n - (n//1000000000)*1000000000)
        return s
    if n < 1000000000000000: # and n >= 1000000000
        s = getNum(n//1000000000000) + ' trillion'
        if n % 1000000000000:
            s += ' ' + getNum(n - (n//1000000000000)*1000000000000)
        return s
    else:
        return 'infinity'

def __main__():
    while True:
        i = raw_input("Enter a number or 'q' to quit: ")
        if i in ('q','quit','exit'): break
        print getNum(i)

if __name__ == '__main__': __main__()

This could be used in producing html, or in any other place where you need numbers spelled out. I don't know why anyone would need numbers in the trillions spelled out.

1 comment

Chris Gahan 19 years, 10 months ago  # | flag

Fancier Algorithm! I wrote something like this a while back, and it does numbers up to 100 digits long! :D

http://epitaph.darkillustrated.org/bignums.php

It's in PHP, but it's nice and readable.

Created by Robb Tolliver on Fri, 21 May 2004 (PSF)
Python recipes (4591)
Robb Tolliver's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks