Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an amount to Indian Notation in Python

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

My code: I have the following Python implementation:

import decimal
def currencyInIndiaFormat(n):
  d = decimal.Decimal(str(n))
  if d.as_tuple().exponent < -2:
    s = str(n)
  else:
    s = '{0:.2f}'.format(n)
  l = len(s)
  i = l-1;
  res = ''
  flag = 0
  k = 0
  while i>=0:
    if flag==0:
      res = res + s[i]
      if s[i]=='.':
        flag = 1
    elif flag==1:
      k = k + 1
      res = res + s[i]
      if k==3 and i-1>=0:
        res = res + ','
        flag = 2
        k = 0
    else:
      k = k + 1
      res = res + s[i]
      if k==2 and i-1>=0:
        res = res + ','
        flag = 2
        k = 0
    i = i - 1

  return res[::-1]

def main():
  n = 100.52
  print "INR " + currencyInIndiaFormat(n)  # INR 100.52
  n = 1000.108
  print "INR " + currencyInIndiaFormat(n)  # INR 1,000.108
  n = 1200000
  print "INR " + currencyInIndiaFormat(n)  # INR 12,00,000.00

main()

My Question: Is there a way to make my currencyInIndiaFormat function shorter, more concise and clean ? / Is there a better way to write my currencyInIndiaFormat function ?

Note: My question is mainly based on Python implementation of the above stated problem. It is not a duplicate of previously asked questions regarding conversion of currency to Indian format.

Indian Currency Format:

For example, numbers here are represented as:

1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000

Refer Indian Numbering System

like image 231
User_Targaryen Avatar asked Dec 03 '16 19:12

User_Targaryen


People also ask

How do you display money in Python?

Formatting a string as dollars and cents results in the form: ${dollars}. {cents} , with commas separating every third digit. For example, 1500.2 would be formatted as $1,500.20 .

How do you convert a number to a million in Python?

intword(value, format='%. For example, 1_000_000 becomes "1.0 million", 1200000 becomes "1.2 million" and "1_200_000_000" becomes "1.2 billion". Supports up to decillion (33 digits) and googol (100 digits). Integer to convert.


1 Answers

def formatINR(number):
    s, *d = str(number).partition(".")
    r = ",".join([s[x-2:x] for x in range(-3, -len(s), -2)][::-1] + [s[-3:]])
    return "".join([r] + d)

It's simple to use:

print(formatINR(123456))

Output

1,23,456
like image 57
pgksunilkumar Avatar answered Sep 22 '22 08:09

pgksunilkumar