A little script i've written to convert an amount of upto 14 digits before the decimal into words.I have a 14 digit limit which conforms with the accounting package tally which is predominantly used here.Million, billions trillions etc aren't used to decribe large sums of money but lakhs and crores are used instead..
XX,XX,XXX
The indian format does not seperate the number in 3's as done in the US here its 2-2-3
So for 14 digits the separation is as follows
XX,XX,XXX,XX,XX,XXX
instructions: paste the code and call the the in_words() function passing it a float formatted to 2 digits after the decimal.
#Constants
ONES={0:'',1:'One',2:'Two',3:'Three',4:'Four',
5:'Five',6:'Six',7:'Seven',8:'Eight',
9:'Nine',10:'Ten',11:'Eleven',12:'Twelve',
13:'Thirteen',14:'Fourteen',15:'Fifteen',
16:'Sixteen',17:'Seventeen',18:'Eighteen',19:'Nineteen'}
TENS={2:'Twenty',3:'Thirty',4:'Forty',5:'Fifty',6:'Sixty',7:'Seventy',8:'Eighty',9:'Ninety'}
#Functionsdef parse_amt2words(ns):
ns1=ns[-3:]
ns2=ns[-5:-3]
ns3=ns[-7:-5]
if len(ns1)>0 and int(ns1)>0:
if len(ns1[-2:-1])>0 and int(ns1[-2:-1])>1:
a= '%s %s'%(TENS[int(ns1[-2:-1])],ONES[int(ns1[-1:])])
else:
a= '%s'%(ONES[int(ns1[-2:])],)
if len(ns1[-3:-2])>0 and int(ns1[-3:-2])>0:
a= '%s Hundred %s'%(ONES[int(ns1[-3:-2])],a)
if len(ns2)>0 and int(ns2)>0:
if len(ns2[-2:-1])>0 and int(ns2[-2:-1])>1:
a= '%s %s Thousand %s'%(TENS[int(ns2[-2:-1])],ONES[int(ns2[-1:])],a)
else:
a= '%s Thousand %s'%(ONES[int(ns2[-2:])],a)
if len(ns3)>0 and int(ns3)>0:
if len(ns3[-2:-1])>0 and int(ns3[-2:-1])>1:
a= '%s %s Lakh %s'%(TENS[int(ns3[-2:-1])],ONES[int(ns3[-1:])],a)
else:
a= '%s Lakh %s'%(ONES[int(ns3[-2:])],a)
return ' '.join(a.split())
#split into 7 chunks.. since its to be used with tally which supports 14 digits -done manually
def amt2words(n):
ns=str(n)
if len(ns)>14:
return 'Number too large'
if len(ns)<=7:
return '%s'%(parse_amt2words(ns[-7:]),)
else:
return '%s Crore %s'%(parse_amt2words(ns[-14:-7]),parse_amt2words(ns[-7:]))
#take the number seperate at decimal point for decimal use 2 digits only
def in_words(x):
#return mdc_report_func.amt2words(int(x))
if isinstance(x,float):
rs=int(x)
ps=int(str(x)[-2:])
elif isinstance(x,int):
rs=int(x)
ps=0
else:
return x
if rs>0:
rs1=amt2words(rs)
else:
rs1=''
if ps>0:
ps1=' And %s Paise'%(amt2words(ps),)
else:
ps1=''
y = '%s%s Only'%(rs1,ps1)
return y
May not the best or even the best piece of code to do this task but it took me about 20 minutes to do and it works so.. use it at your own risk if you need help to understand it drop me a line..
