top of page
Writer's pictureThe Tech Platform

Write a Program to Convert Number to Words in Python

Example 1, we are going to convert a number to its wording. For instance, if the number is 12, the wordings will be “one-two”. A similar thing will be done for the rest of the inputs.


Example 1:

arr = ['zero','one','two','three','four','five','six','seven','eight','nine']
 
def number_2_word(n):
 
    # If all the digits are encountered return blank string
    if(n==0):
        return ""
     
    else:
        # compute spelling for the last digit
        small_ans = arr[n%10]
 
        # keep computing for the previous digits and add the spelling for the last digit
        ans = number_2_word(int(n/10)) + small_ans + " "
     
    # Return the final answer
    return ans
 
n = int(input())
print("Number Entered was : ", n)
print("In English: ",end="")
print(number_2_word(n))

Output:


 

Example 2: we are going to convert the number to its digital-place wise. For instance, if the number is 12, then the result will be twelve. Similar thing will be done for rest of the inputs.


Example 2:

Pre-defined Input

# convert a single-digit or two-digit number into words
def convertToDigit(n, suffix):
 
    # if `n` is zero
    if n == 0:
        return EMPTY
 
    # split `n` if it is more than 19
    if n > 19:
        return Y[n // 10] + X[n % 10] + suffix
    else:
        return X[n] + suffix
 
 
# convert a given number (max 9-digits) into words
def convert(n):
    # add digits at ten million and hundred million place
    result = convertToDigit((n // 1000000000) % 100, 'Billion, ')
 
    # add digits at ten million and hundred million place
    result += convertToDigit((n // 10000000) % 100, 'Crore, ')
 
    # add digits at hundred thousand and one million place
    result += convertToDigit(((n // 100000) % 100), 'Lakh, ')
 
    # add digits at thousand and tens thousand place
    result += convertToDigit(((n // 1000) % 100), 'Thousand, ')
 
    # add digit at hundred place
    result += convertToDigit(((n // 100) % 10), 'Hundred ')
 
    if n > 100 and n % 100:
        result += 'and '
 
    # add digits at ones and tens place
    result += convertToDigit((n % 100), '')
 
    return result.strip().rstrip(',').replace(', and', ' and')
 
 
#convert numbers to words
if __name__ == '__main__':
    EMPTY = ''
 
    X = [EMPTY, 'One ', 'Two ', 'Three ', 'Four ', 'Five ', 'Six ', 'Seven ',
        'Eight ', 'Nine ', 'Ten ', 'Eleven ', 'Twelve ', 'Thirteen ', 'Fourteen ',
        'Fifteen ', 'Sixteen ', 'Seventeen ', 'Eighteen ', 'Nineteen ']
 
    Y = [EMPTY, EMPTY, 'Twenty ', 'Thirty ', 'Forty ', 'Fifty ',
        'Sixty ', 'Seventy ', 'Eighty ', 'Ninety ']
 
    print(convert(0))
    print(convert(7000))
    print(convert(75432))
    print(convert(997751076))
    print(convert(6147493690))

Output:



The Tech Platform

Recent Posts

See All

Comments


bottom of page