Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 452
CarlosRibet Avatar asked Apr 01 '11 12:04

CarlosRibet


People also ask

How do you format a thousands separator?

The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.

How do you add a thousands separator in Python?

Using the modern f-strings is, in my opinion, the most Pythonic solution to add commas as thousand-separators for all Python versions above 3.6: f'{1000000:,}' . The inner part within the curly brackets :, says to format the number and use commas as thousand separators.


2 Answers

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' 
like image 158
Mikel Avatar answered Oct 16 '22 11:10

Mikel


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' 
like image 40
utdemir Avatar answered Oct 16 '22 10:10

utdemir