HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Convert an amount to Indian Notation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertindiannotationamount

Problem

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

import decimal
def currencyInIndiaFormat(n):
  d = decimal.Decimal(str(n))
  if d.as_tuple().exponent =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()


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

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

Solution


  1. Style guides



  • leave two empty lines before each function (when you're not inside of a class)



  • Python is not C; don't use ;



  • put a space before and after operands. i>=0 will become i >= 0, s[i]=='.' will become s[i] == '.' and so on.



  • use the snake_case notation for function names: currencyInIndiaFormat(..) will become currency_in_indian_format(..)



  • use format() instead of + notation: e.g: print "INR " + currencyInIndiaFormat(n) might be print "INR {}".format(currencyInIndiaFormat(n))



  • also, I'd recommend you use print('w/e you want here') so that your code can be python 3 compatible.



  • use 4 spaces for indentation instead of 2.



  • use augmented assignments where you can: res = res + s[i] can be written as res += s[i]



  • add docstrings to your functions to describe what their purpose are



If you want to read more about Python style guide, you should start from here.

Preview:

import decimal

def currency_in_indian_format(n):
    """ Convert a number (int / float) into indian formatting style """
    d = decimal.Decimal(str(n))

    if d.as_tuple().exponent = 0:
        if flag == 0:
            res += s[i]
            if s[i] == '.':
                flag = 1
        elif flag == 1:
            k += 1
            res += s[i]
            if k == 3 and i - 1 >= 0:
                res += ','
                flag = 2
                k = 0
        else:
            k += 1
            res += s[i]
            if k == 2 and i - 1 >= 0:
                res += ','
                flag = 2
                k = 0
        i -= 1

    return res[::-1]

def main():
    n = 100.52
    print("INR {}".format(currency_in_indian_format(n)))  # INR 100.52
    n = 1000.108
    print("INR {}".format(currency_in_indian_format(n)))  # INR 1,000.108
    n = 1200000
    print("INR {}".format(currency_in_indian_format(n)))  # INR 12,00,000.00

if __name__ == '__main__':
    main()


NOTE: I've also added if __name__ == '__main__'. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
  1. Algorithm



As I said in the comments, I would strongly recommend using the existing builtin module locale, which is doing exactly what you want:

Example code (it's working if you have the locale set on your machine - so that would be an ugly constraint):

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_IN.utf8')  # if this doesn't work, you might try as well: locale.setlocale(locale.LC_ALL, '')
'en_IN'
>>> locale.format("%d", 1255000, grouping=True)
'12,55,000'


I'll let others to comment on your code regarding the efficiency of the algorithm you implemented and methods to make it shorter / better.

Code Snippets

import decimal


def currency_in_indian_format(n):
    """ Convert a number (int / float) into indian formatting style """
    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, k = '', 0, 0
    while i >= 0:
        if flag == 0:
            res += s[i]
            if s[i] == '.':
                flag = 1
        elif flag == 1:
            k += 1
            res += s[i]
            if k == 3 and i - 1 >= 0:
                res += ','
                flag = 2
                k = 0
        else:
            k += 1
            res += s[i]
            if k == 2 and i - 1 >= 0:
                res += ','
                flag = 2
                k = 0
        i -= 1

    return res[::-1]


def main():
    n = 100.52
    print("INR {}".format(currency_in_indian_format(n)))  # INR 100.52
    n = 1000.108
    print("INR {}".format(currency_in_indian_format(n)))  # INR 1,000.108
    n = 1200000
    print("INR {}".format(currency_in_indian_format(n)))  # INR 12,00,000.00


if __name__ == '__main__':
    main()
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_IN.utf8')  # if this doesn't work, you might try as well: locale.setlocale(locale.LC_ALL, '')
'en_IN'
>>> locale.format("%d", 1255000, grouping=True)
'12,55,000'

Context

StackExchange Code Review Q#148853, answer score: 8

Revisions (0)

No revisions yet.