CarlosRibet
CarlosRibet

Reputation: 791

Add 'decimal-mark' thousands separators to a number

How do I format 1000000 to 1.000.000 in Python? where the '.' is the decimal-mark thousands separator.

Upvotes: 66

Views: 74274

Answers (9)

utdemir
utdemir

Reputation: 27216

To format 1123000 as 1,123,000, use the format function:

e.g.:

>>> format(1123000,',d')
'1,123,000'

See also: https://docs.python.org/release/3.11.0/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator

Upvotes: 22

JATIN
JATIN

Reputation: 320

DIY solution

def format_number(n):
    result = ""
    for i, digit in enumerate(reversed(str(n))):
        if i != 0 and (i % 3) == 0:
            result += ","
        result += digit
    return result[::-1]

built-in solution

def format_number(n):
    return "{:,}".format(n)

Upvotes: 1

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

Strange that nobody mentioned a straightforward solution with regex:

import re
print(re.sub(r'(?<!^)(?=(\d{3})+$)', r'.', "12345673456456456"))

Gives the following output:

12.345.673.456.456.456

It also works if you want to separate the digits only before comma:

re.sub(r'(?<!^)(?=(\d{3})+,)', r'.', "123456734,56456456")

gives:

123.456.734,56456456

the regex uses lookahead to check that the number of digits after a given position is divisible by 3.


Update 2021: Please use this for scripting only (i.e. only in situation where you can destroy the code after using it). When used in an application, this approach would constitute a ReDoS.

Upvotes: 1

Mikel
Mikel

Reputation: 25596

If you want to add a thousands separator, you can write:

>>> '{0:,}'.format(1000000)
'1,000,000'

But it only works in Python 2.7 and above.

See format string syntax.

In older versions, you can use locale.format():

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_AU.utf8'
>>> locale.format('%d', 1000000, 1)
'1,000,000'

the added benefit of using locale.format() is that it will use your locale's thousands separator, e.g.

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')
'de_DE.utf-8'
>>> locale.format('%d', 1000000, 1)
'1.000.000'

Upvotes: 118

PythonProgrammi
PythonProgrammi

Reputation: 23443

An idea

def itanum(x):
    return format(x,',d').replace(",",".")

>>> itanum(1000)
'1.000'

Upvotes: 6

Marcus Seuser
Marcus Seuser

Reputation: 71

Drawing on the answer by Mikel, I implemented his solution like this in my matplotlib plot. I figured some might find it helpful:

ax=plt.gca()
ax.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, loc: locale.format('%d', x, 1)))

Upvotes: 1

Anand Tripathi
Anand Tripathi

Reputation: 16126

Here's only a alternative answer. You can use split operator in python and through some weird logic Here's the code

i=1234567890
s=str(i)
str1=""
s1=[elm for elm in s]
if len(s1)%3==0:
    for i in range(0,len(s1)-3,3):
        str1+=s1[i]+s1[i+1]+s1[i+2]+"."
    str1+=s1[i]+s1[i+1]+s1[i+2]
else:
    rem=len(s1)%3
    for i in range(rem):
        str1+=s1[i]
    for i in range(rem,len(s1)-1,3):
        str1+="."+s1[i]+s1[i+1]+s1[i+2]

print str1

Output

1.234.567.890

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

Using itertools can give you some more flexibility:

>>> from itertools import zip_longest
>>> num = "1000000"
>>> sep = "."
>>> places = 3
>>> args = [iter(num[::-1])] * places
>>> sep.join("".join(x) for x in zip_longest(*args, fillvalue=""))[::-1]
'1.000.000'

Upvotes: 1

jpihl
jpihl

Reputation: 8071

Just extending the answer a bit here :)

I needed to both have a thousandth separator and limit the precision of a floating point number.

This can be achieved by using the following format string:

> my_float = 123456789.123456789
> "{:0,.2f}".format(my_float)
'123,456,789.12'

This describes the format()-specifier's mini-language:

[[fill]align][sign][#][0][width][,][.precision][type]

Source: https://www.python.org/dev/peps/pep-0378/#current-version-of-the-mini-language

Upvotes: 21

Related Questions