Convert an amount to Indian Notation in Python

前端 未结 5 708
离开以前
离开以前 2021-01-02 03:40

Problem: I need to convert an amount to Indian currency format

My code: I have the following Python implementation:

5条回答
  •  孤城傲影
    2021-01-02 04:24

    Here is the other way around:

    import re
    def in_for(value):
        value,b=str(value),''
        value=''.join(map(lambda va:va if re.match(r'[0-9,.]',va) else '',value))
        val=value
        if val.count(',')==0:
            v,c,a,cc,ii=val,0,[3,2,2],0,0
            val=val[:val.rfind('.')] if val.rfind('.')>=0  else val
            for i in val[::-1]:
                if c==ii and c!=0:
                    ii+=a[cc%3]
                    b=','+i+b
                    cc+=1  
                else:
                    b=i+b
                c+=1
            b=b[1:] if b[0]==',' else b
            val=b+v[value.rfind('.'):]  if value.rfind('.')>=0  else b
        else:
            val=str(val).strip('()').replace(' ','')
        v=val.rfind('.')
        if v>0:
            val=val[:v+3]
        return val.rstrip('0').rstrip('.') if '.' in val else val
    
    print(in_for('1000000000000.5445'))
    

    Output will be:

    10,000,00,00,000.54 
    

    (As mentioned in wikipedia indian number system Ex:67,89,000,00,00,000)

提交回复
热议问题