Converting numbers to words
Brian Allen Vanderburg II
BrianVanderburg2 at aim.com
Fri Feb 6 04:20:35 CET 2009
todpose at hotmail.com wrote:
>
> I've been trying to figure this out for over 2 hours and I'm really
frustrated right now.
>
> I first made Python to ask user to input height in meters. If user
puts certain value in meter, then it converts it to feet and inches as
follows:
>
>
> Enter the height (in metres): 1.6
>
> It is 5 feet, 3 inches high.
>
>
> What I want to do is to make it type only words. For example, instead
of its saying, "It is 5 feet, 3 inches high," I want it to say, "it is
five feet, three inches high."
> I'd appreciate any suggestions.
I made something similar in the past. First I break it into two
functions, one function handles 0-999 and return '' for zero or a
meaningful value for 999, another function handles how many groups there
are and for each one, gets the value for it calls the first function,
and appends the correct word. This only works for the English language
though
Brian Vanderburg II
num_words1 = ("zero", # not used
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen")
num_words2 = ("twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety")
num_words3 = ("thousand",
"million",
"billion",
"trillion",
"quadrillion")
def word_func1(value):
# value can be from 0 to 999
result = ''
if value == 0:
return result
# Handle hundreds
if value >= 100:
hvalue = int(value / 100)
if result:
result += ' '
result += num_words1[hvalue]
result += ' hundred'
value -= (hvalue * 100)
if value == 0:
return result
# Handle 1-19
if value < 20:
if result:
result += ' '
result += num_words1[value]
return result
# Handle 10s (20-90)
tvalue = int(value / 10)
if result:
result += ' '
result += num_words2[tvalue - 2]
value -= (tvalue * 10)
if value == 0:
return result
# Handle ones
if result:
result += ' '
result += num_words1[value]
return result
def word_func2(value):
result = ''
if value == 0:
return 'zero'
# Determine support values
divider = 1
l = len(num_words3)
for i in range(l):
divider *= 1000
for i in range(l):
if value >= divider:
dvalue = int(value / divider)
if result:
result += ' '
result += word_func1(dvalue)
result += ' '
result += num_words3[l - i - 1]
value -= (dvalue * divider)
divider /= 1000
if value > 0:
if result:
result += ' '
result += word_func1(value)
return result
number_to_word = word_func2
More information about the Python-list
mailing list