2

I have a number like: 100 I am showing here as it. But when I am trying to show a number as 1000 then want to display as 1,000.& so on like 1,00,000 likewise.

Below structure

Number Formatted As

10 10

100 100

1000 1,000

10000 10,000

100000 1,00,000

1000000 10,00,000

10000000 1,00,00,000

100000000 10,00,00,000

1000000000 1,00,00,00,000

10000000000 10,00,00,00,000

All the above things I want to do in python.

I thought of using regex but couldn't get an way how to proceed.

Any one having any idea?

danny
  • 983
  • 1
  • 7
  • 13

2 Answers2

6

Updated: This code now supports both int and float numbers!

You could write a little number-to-string converting function yourself, like this one:

def special_format(n):
    s, *d = str(n).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(special_format(1))
print(special_format(12))
print(special_format(123))
print(special_format(1234))
print(special_format(12345))
print(special_format(123456))
print(special_format(12345678901234567890))
print(special_format(1.0))
print(special_format(12.34))
print(special_format(1234567890.1234567890))

The above example would result in this output:

1
12
123
1,234
12,345
1,23,456
1,23,45,67,89,01,23,45,67,890
1.0
12.34
1,23,45,67,890.1234567

See this code running on ideone.com

Byte Commander
  • 6,506
  • 6
  • 44
  • 71
5

I recognize this way of separating numbers as the one used in India. So I think you can get what you want using locale:

import locale
locale.setlocale(locale.LC_NUMERIC, 'hi_IN')
locale.format("%d", 10000000000, grouping=True)

The exact locale to use may be different on your system; try locale -a | grep IN to get a list of Indian locales you have installed.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • I tried with using as: **locale.setlocale(locale.LC_NUMERIC, '')**. Worked fine for me. – danny May 09 '16 at 07:05
  • @danny: Yeah, that's using the default locale on your machine, which may be fine since you're probably doing this to match your own regional settings. People running your code on systems configured for other countries would need an explicit locale name if they want the to print in "lakh" style. – John Zwinck May 09 '16 at 07:16