numbers to words converter python program

Solutions on MaxInterview for numbers to words converter python program by the best coders in the world

showing results for - "numbers to words converter python program"
Rafael
14 Apr 2017
1
2# Number to Words
3
4# Main Logic
5ones = ('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine')
6
7twos = ('Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen')
8
9tens = ('Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety', 'Hundred')
10
11suffixes = ('', 'Thousand', 'Million', 'Billion')
12
13def process(number, index):
14    
15    if number=='0':
16        return 'Zero'
17    
18    length = len(number)
19    
20    if(length > 3):
21        return False
22    
23    number = number.zfill(3)
24    words = ''
25 
26    hdigit = int(number[0])
27    tdigit = int(number[1])
28    odigit = int(number[2])
29    
30    words += '' if number[0] == '0' else ones[hdigit]
31    words += ' Hundred ' if not words == '' else ''
32    
33    if(tdigit > 1):
34        words += tens[tdigit - 2]
35        words += ' '
36        words += ones[odigit]
37    
38    elif(tdigit == 1):
39        words += twos[(int(tdigit + odigit) % 10) - 1]
40        
41    elif(tdigit == 0):
42        words += ones[odigit]
43
44    if(words.endswith('Zero')):
45        words = words[:-len('Zero')]
46    else:
47        words += ' '
48     
49    if(not len(words) == 0):    
50        words += suffixes[index]
51        
52    return words;
53    
54def getWords(number):
55    length = len(str(number))
56    
57    if length>12:
58        return 'This program supports upto 12 digit numbers.'
59    
60    count = length // 3 if length % 3 == 0 else length // 3 + 1
61    copy = count
62    words = []
63 
64    for i in range(length - 1, -1, -3):
65        words.append(process(str(number)[0 if i - 2 < 0 else i - 2 : i + 1], copy - count))
66        count -= 1;
67
68    final_words = ''
69    for s in reversed(words):
70        temp = s + ' '
71        final_words += temp
72    
73    return final_words
74# End Main Logic
75
76# Reading number from user
77number = int(input('Enter any number: '))
78print('%d in words is: %s' %(number, getWords(number)))
79