Convert amount to word in Python In Indian Format

后端 未结 2 883
离开以前
离开以前 2021-01-29 05:02

How to convert amount to word in Indian?

I was using num2words library but its is presenting wrong set of words while presenting \'lakhs\' and \'crores\'.

For ex

2条回答
  •  醉话见心
    2021-01-29 05:38

    you can split the decimal and fractional part can call num2word function twice on number and other on fractional part

    import math
    def num2words(num):
        under_20 = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']
        tens = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']
        above_100 = {100: 'Hundred',1000:'Thousand', 100000:'Lakhs', 10000000:'Crores'}
    
        if num < 20:
             return under_20[(int)(num)]
    
        if num < 100:
            return tens[(int)(num/10)-2] + ('' if num%10==0 else ' ' + under_20[(int)(num%10)])
    
        # find the appropriate pivot - 'Million' in 3,603,550, or 'Thousand' in 603,550
        pivot = max([key for key in above_100.keys() if key <= num])
    
        return num2words((int)(num/pivot)) + ' ' + above_100[pivot] + ('' if num%pivot==0 else ' ' + num2words(num%pivot))
    
    num="5.12"
    print(num2words(int(num.split(".")[0])))
    print(num2words(int(num.split(".")[1])))
    

    https://ide.geeksforgeeks.org/J7zsZyIT6m

提交回复
热议问题