65

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

smci
  • 32,567
  • 20
  • 113
  • 146
CarlosRibet
  • 781
  • 1
  • 5
  • 5
  • 3
    Please clearify your question. Show some code, mention the data type of the object you want to print, give example output. – Sven Marnach Apr 01 '11 at 12:52
  • You cannot have more than one decimal point in a number. What is `1.000.000` supposed to mean? Do you mean commas? – Noufal Ibrahim Apr 01 '11 at 13:00
  • 31
    @Noufal: in some locales, `.` is used instead of `,` to separate thousands. – Wooble Apr 01 '11 at 13:01
  • Really? I wasn't aware of that. I don't think they'd be called "decimal points" in those locales though. – Noufal Ibrahim Apr 01 '11 at 13:08
  • 3
    @NoufalIbrahim, This called decimal mark and [Wikipedia page](https://en.wikipedia.org/wiki/Decimal_mark) explains which countries use different decimal mark styles. – Eir Nym Jun 25 '15 at 19:53
  • Those interested in this issue may want to [look at my answer](http://stackoverflow.com/questions/15345438/how-to-add-thousands-separator-to-a-number-that-has-been-converted-to-a-string-i/35957384#35957384) (to a similar question) which explores the limitations of using the `format()` solution and has code written to do the job. – mattst Mar 12 '16 at 12:19

9 Answers9

119

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'
MendelG
  • 14,885
  • 4
  • 25
  • 52
Mikel
  • 24,855
  • 8
  • 65
  • 66
  • 1
    If you are working with currencies, you can also use the babel.numbers.format_currency helper. – semente Dec 06 '12 at 18:26
  • 3
    For floats the syntax is `{:6,.2f}` where `6` is the field width and `2` is the precision. The placement of the comma tripped me up a bit. – nathanielobrown Apr 27 '16 at 18:15
  • You can check all installed locales with "$ locale -a", a default Ubuntu installation for instance will only have en_US so this is not a viable strategy. – xApple Apr 11 '17 at 12:46
21

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'
nmichaels
  • 49,466
  • 12
  • 107
  • 135
utdemir
  • 26,532
  • 10
  • 62
  • 81
20

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

jpihl
  • 7,941
  • 3
  • 37
  • 50
  • 4
    what if he wanted to get the following output: `'123.456.789,12'` ? – dot.Py Feb 26 '16 at 20:17
  • @dot.Py he could set an appropriate locale `locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')` then use `("{:.%dn}" % (math.log10(my_float)+3)).format(my_float)` however the 'n' format string is the locale aware equivalent of 'g' rather than 'f' so the precision field gets messy. – Duncan Jul 05 '16 at 08:47
6

An idea

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

>>> itanum(1000)
'1.000'
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34
2

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.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
1

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'
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

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)))
Marcus Seuser
  • 71
  • 1
  • 4
1

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)
JATIN
  • 170
  • 1
  • 7
0

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
Anand Tripathi
  • 14,556
  • 1
  • 47
  • 52