Add 'decimal-mark' thousands separators to a number

PythonFormatLocaleNumber FormattingDigit Separator

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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'

Solution 2 - Python

I didn't really understand it; but here is what I understand:

You want to convert 1123000 to 1,123,000. You can do that by using format:

http://docs.python.org/release/3.1.3/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator

Example:

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

Solution 3 - Python

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

Solution 4 - Python

An idea

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

>>> itanum(1000)
'1.000'

Solution 5 - Python

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'

Solution 6 - Python

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)))

Solution 7 - Python

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.

Solution 8 - Python

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)

Solution 9 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarlosRibetView Question on Stackoverflow
Solution 1 - PythonMikelView Answer on Stackoverflow
Solution 2 - PythonutdemirView Answer on Stackoverflow
Solution 3 - PythonjpihlView Answer on Stackoverflow
Solution 4 - PythonPythonProgrammiView Answer on Stackoverflow
Solution 5 - PythonEugene YarmashView Answer on Stackoverflow
Solution 6 - PythonMarcus SeuserView Answer on Stackoverflow
Solution 7 - PythonAndrey TyukinView Answer on Stackoverflow
Solution 8 - PythonJATINView Answer on Stackoverflow
Solution 9 - PythonAnand TripathiView Answer on Stackoverflow