Wednesday, February 1, 2017

Number To String Python

Tags

Following Code will convert a number entered by user to the Same Number in Words

Code::

def numtostring(n):
    if (n==0):return ""
    elif(n==1):return "one"
    elif(n==2):return "two"
    elif(n==3):return "three"
    elif(n==4):return "four"
    elif(n==5):return "five"
    elif(n==6):return "six"
    elif(n==7):return "seven"
    elif(n==8):return "eight"
    elif(n==9):return "nine"
    elif(n==10):return "ten"
    elif(n==11):return "eleven"
    elif(n==12):return "twelve"
    elif(n==13):return "thirteen"
    elif(n==14):return "fourteen"
    elif(n==15):return "fifteen"
    elif(n==16):return "sixteen"
    elif(n==17):return "seventeen"
    elif(n==18):return "eighteen"
    elif(n==19):return "nineteen"
    elif(n<=29):return "twenty "+numtostring(n%10)
    elif(n<=39):return "thirty "+numtostring(n%10)
    elif(n<=49):return "forty "+numtostring(n%10)
    elif(n<=59):return "fifty "+numtostring(n%10)
    elif(n<=69):return "sixty "+numtostring(n%10)
    elif(n<=79):return "seventy "+numtostring(n%10)
    elif(n<=89):return "eighty "+numtostring(n%10)
    elif(n<=99):return "ninety "+numtostring(n%10)

def convert(n):
    if(n<=99):
        return numtostring(n)
    elif(n<=999):
        return numtostring(n//100)+' hundred '+numtostring(n%100)
    elif(n<=9999):
        return numtostring(n//1000)+' thousand '+numtostring((n//100)%10)+' hundred '+numtostring((n%100))


i=int(input("Enter Any Number Upto 9999: "))
print(convert(i))
     
Output: