0% found this document useful (0 votes)
6 views4 pages

Convert Numbers to Words in Python

The document contains functions to convert numbers to words in English. It takes a number as input, breaks it into groups of 3 digits and converts each group to words by using lists of number names.

Uploaded by

kimblytheee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Convert Numbers to Words in Python

The document contains functions to convert numbers to words in English. It takes a number as input, breaks it into groups of 3 digits and converts each group to words by using lists of number names.

Uploaded by

kimblytheee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

NUMBER STRING CODE

n1 = ('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine')

n2 = ('Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen',


'Nineteen')

n3 = ('Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety')

def process(number, index):

if number == '0':

return 'Zero'

length = len(number)

if (length > 3):

return False

number = [Link](3)

words = ''

hdigit = int(number[0])

tdigit = int(number[1])

odigit = int(number[2])

words += '' if number[0] == '0' else n1[hdigit]

words += ' Hundred ' if not words == '' else ''

if (tdigit > 1):

words += n3[tdigit - 2]

words += ' '


words += n1[odigit]

elif (tdigit == 1):

words += n2[(int(tdigit + odigit) % 10) - 1]

elif (tdigit == 0):

words += n1[odigit]

if ([Link]('Zero')):

words = words[:-len('Zero')]

else:

words += ' '

return words;

def getWords(number):

length = len(str(number))

if number < 0:

return 'Invalid Integer Number'

if length > 12:

return 'This program supports upto 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):

[Link](process(str(number)[0 if i - 2 < 0 else i - 2: i + 1], copy - count))

count -= 1;

final_words = ''

for s in reversed(words):

temp = s + ' '

final_words += temp

return final_words

number = int(input('Enter any number: '))

print('You have entered %s' % (getWords(number)))

You might also like