-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnum2words.py
More file actions
executable file
·81 lines (61 loc) · 1.92 KB
/
num2words.py
File metadata and controls
executable file
·81 lines (61 loc) · 1.92 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
# This converts number to words
# Originally from https://hackr.io/blog/python-projects
# TODO: Add command line parameter to provide number.
ones = (
'Zero', 'One', 'Two', 'Three', 'Four',
'Five', 'Six', 'Seven', 'Eight', 'Nine'
)
twos = (
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen',
'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'
)
tens = (
'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty',
'Seventy', 'Eighty', 'Ninety', 'Hundred'
)
suffixes = (
'', 'Thousand', 'Million', 'Billion'
)
def fetch_words(number, index):
if number == '0': return 'Zero'
number = number.zfill(3)
hundreds_digit = int(number[0])
tens_digit = int(number[1])
ones_digit = int(number[2])
words = '' if number[0] == '0' else ones[hundreds_digit]
if words != '':
words += ' Hundred '
if tens_digit > 1:
words += tens[tens_digit - 2]
words += ' '
words += ones[ones_digit]
elif(tens_digit == 1):
words += twos[((tens_digit + ones_digit) % 10) - 1]
elif(tens_digit == 0):
words += ones[ones_digit]
if(words.endswith('Zero')):
words = words[:-len('Zero')]
else:
words += ' '
if len(words) != 0:
words += suffixes[index]
return words
def convert_to_words(number):
length = len(str(number))
if length > 12:
return 'This program supports a maximum of 12 digit numbers.'
count = length // 3 if length % 3 == 0 else length // 3 + 1
copy = count
words = []
for i in range(length - 1, -1, -3):
words.append(fetch_words(
str(number)[0 if i - 2 < 0 else i - 2 : i + 1], copy - count))
count -= 1
final_words = ''
for s in reversed(words):
final_words += (s + ' ')
return final_words
if __name__ == '__main__':
number = int(input('Enter any number: '))
print('%d in words is: %s' %(number, convert_to_words(number)))