|
| 1 | +''' |
| 2 | +Numbers To Words |
| 3 | +------------------------------------------------------------- |
| 4 | +''' |
| 5 | + |
| 6 | + |
| 7 | +ones = ( |
| 8 | + 'Zero', 'One', 'Two', 'Three', 'Four', |
| 9 | + 'Five', 'Six', 'Seven', 'Eight', 'Nine' |
| 10 | + ) |
| 11 | + |
| 12 | +twos = ( |
| 13 | + 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', |
| 14 | + 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen' |
| 15 | + ) |
| 16 | + |
| 17 | +tens = ( |
| 18 | + 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', |
| 19 | + 'Seventy', 'Eighty', 'Ninety', 'Hundred' |
| 20 | + ) |
| 21 | + |
| 22 | +suffixes = ( |
| 23 | + '', 'Thousand', 'Million', 'Billion' |
| 24 | + ) |
| 25 | + |
| 26 | +def fetch_words(number, index): |
| 27 | + if number == '0': return 'Zero' |
| 28 | + |
| 29 | + number = number.zfill(3) |
| 30 | + hundreds_digit = int(number[0]) |
| 31 | + tens_digit = int(number[1]) |
| 32 | + ones_digit = int(number[2]) |
| 33 | + |
| 34 | + words = '' if number[0] == '0' else ones[hundreds_digit] |
| 35 | + |
| 36 | + if words != '': |
| 37 | + words += ' Hundred ' |
| 38 | + |
| 39 | + if tens_digit > 1: |
| 40 | + words += tens[tens_digit - 2] |
| 41 | + words += ' ' |
| 42 | + words += ones[ones_digit] |
| 43 | + elif(tens_digit == 1): |
| 44 | + words += twos[((tens_digit + ones_digit) % 10) - 1] |
| 45 | + elif(tens_digit == 0): |
| 46 | + words += ones[ones_digit] |
| 47 | + |
| 48 | + if(words.endswith('Zero')): |
| 49 | + words = words[:-len('Zero')] |
| 50 | + else: |
| 51 | + words += ' ' |
| 52 | + |
| 53 | + if len(words) != 0: |
| 54 | + words += suffixes[index] |
| 55 | + |
| 56 | + return words |
| 57 | + |
| 58 | + |
| 59 | +def convert_to_words(number): |
| 60 | + length = len(str(number)) |
| 61 | + if length > 12: |
| 62 | + return 'This program supports a maximum of 12 digit numbers.' |
| 63 | + |
| 64 | + count = length // 3 if length % 3 == 0 else length // 3 + 1 |
| 65 | + copy = count |
| 66 | + words = [] |
| 67 | + |
| 68 | + for i in range(length - 1, -1, -3): |
| 69 | + words.append(fetch_words( |
| 70 | + str(number)[0 if i - 2 < 0 else i - 2 : i + 1], copy - count)) |
| 71 | + |
| 72 | + count -= 1 |
| 73 | + |
| 74 | + final_words = '' |
| 75 | + for s in reversed(words): |
| 76 | + final_words += (s + ' ') |
| 77 | + |
| 78 | + return final_words |
| 79 | + |
| 80 | +if __name__ == '__main__': |
| 81 | + number = int(input('Enter any number: ')) |
| 82 | + print('%d in words is: %s' %(number, convert_to_words(number))) |
0 commit comments