Cardinal number output
Neel Krishnaswami
neelk at brick.cswv.com
Fri Sep 8 20:16:23 EDT 2000
Greg Fortune <gfortune at linuxteams.com> wrote:
> Anyone know of a module or utility function to accept an int and convert
> it to the cardinal number representation? For example, is there
> anything that will convert ints to a format suitable to printing on a
> check?
Here you are. It's only lightly tested and wholly uncommented and
undocumented, but it ought to get you going in the right direction.
>>> english(-12340)
'negative twelve thousand three hundred forty'
-*-*-
author = "Neel Krishnaswami <neelk at alum.mit.edu>"
copyright = "This source code is in the public domain."
import string
def english(n):
pieces = []
if n < 0:
pieces.append("negative")
thousand_powers(-n, 0, pieces)
else:
thousand_powers(n, 0, pieces)
return string.join(pieces, " ")
thousand_words = ["", "thousand", "million", "billion"]
ten_words = ["", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
unit_words = ["zero", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"]
def ten_powers(n, pieces):
if n < 20:
pieces.append(unit_words[n])
else:
tens, units = divmod(n, 10)
pieces.append(ten_words[tens])
if units != 0:
pieces.append(unit_words[units])
def hundred_powers(n, pieces):
hundreds, units = divmod(n, 100)
if hundreds == 0:
ten_powers(units, pieces)
else:
ten_powers(hundreds, pieces)
pieces.append("hundred")
if units != 0:
ten_powers(units, pieces)
def thousand_powers(n, thousand_index, pieces):
millions, mod_millions = divmod(n, 1000000)
hundreds, units = divmod(mod_millions, 100)
if hundreds < 100 and hundreds % 10 != 0:
if millions != 0:
thousand_powers(millions, thousand_index + 2, pieces)
hundred_powers(mod_millions, pieces)
if thousand_index != 0:
pieces.append(thousand_words[thousand_index])
else:
thousands, units = divmod(n, 1000)
if thousands == 0:
if thousand_index == 0:
hundred_powers(units, pieces)
elif units != 0:
hundred_powers(units, pieces)
pieces.append(thousand_words[thousand_index])
else:
thousand_powers(thousands, thousand_index + 1, pieces)
if units != 0:
hundred_powers(units, pieces)
if thousand_index != 0:
pieces.append(thousand_words[thousand_index])
-*-*-
Neel
More information about the Python-list
mailing list