Skip to content

Instantly share code, notes, and snippets.

@msimpson msimpson/numconv
Created Jul 23, 2011

Embed
What would you like to do?
Convert an integer into a spoken number.
#!/usr/bin/env python
# Number to name convertion.
import sys
n = (sys.argv[1] if sys.argv[1].isdigit() else 0) if len(sys.argv)>1 else 0
if len(n)>30:
print("Error: Number too large.")
sys.exit(1)
def trip(n):
n = int(n)
t = int(n%100/10)
h = int(n%1000/100)
o = n%100 if n%100<20 else n%10
s = ["one","two","three","four","five","six",
"seven","eight","nine","ten","eleven","twelve","thirteen",
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
m = ["twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"]
return (s[h-1]+" hundred and " if h>0 else "")+(m[t-2] if t>1 else "")+ \
(" " if t>1 and o>0 else "")+(s[o-1] if o>0 else "")
def conv(n):
n = int(n)
if n<1: return "Zero."
a = [trip(s) for s in [int(n%(1000**d)/(1000**(d-1))) for d in range(1,11)] if s>0]
l = ["","thousand","million","billion","trillion","quadrillion",
"pentillion","hexillion","septillion","octillion"]
s = [a[0]+"."]+[a[i]+" "+l[i]+", " for i in range(1,len(a))]
s = "".join(s[::-1])
return s[0].upper()+s[1:]
print(conv(n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.