0

I am working on an application that presents data to both Indian and US managers.

I'd like to display numbers with western-style comma separation (000,000,000) or Indian style (00,00,00,000) based on the currency being displayed. I don't want to use localize as figures need to be displayed consistently, no matter which region it is being viewed in.

For my purposes, the final three zeroes in each case can be dropped, so that I will either need a comma every third or second character, working from the end.

I'm starting with something like this:

def commas(str, format="US"):
     if format == "IN":
         x = 2 
     elif format == "US":
         x = 3

     new_str = ','.join(str[i:i+x] for i in range(0, len(str), x))

     return new_str

This outputs a number like so: 815,532,89. Is there a way to reverse this so that I can get it to render properly?

martineau
  • 119,623
  • 25
  • 170
  • 301
Adam Starrh
  • 6,428
  • 8
  • 50
  • 89

1 Answers1

1

You can apply the commas to the reversed string and then reverse it again:

def commas(str, format="US"):
     if format == "IN":
         x = 2 
     elif format == "US":
         x = 3

     rev = str[::-1]
     new_str = ','.join(rev[i:i+x] for i in range(0, len(rev), x))[::-1]

     return new_str
jdehesa
  • 58,456
  • 7
  • 77
  • 121