Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thousand separator in format string with floats

I want to have thousand separators in floats. What I'm doing is:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> print '{0:n}'.format(123456.0)
123,456

When the integer part has 7 or more digits it does not work:

>>> print '{0:n}'.format(1234567.0)
1.23457e+06

The workaround that I found is to turn the float into an integer before formating:

>>> print '{0:n}'.format(int(1234567.0))
1,234,567

Is there a format string that would handle all floats without the need to turn it into an integer first?

like image 701
Clodoaldo Neto Avatar asked Apr 19 '12 14:04

Clodoaldo Neto


2 Answers

The locale setting is a bit ugly as it isn't thread-safe and very dependent on what the locale actually does. It might be what you want, but here's Python's internal version (starting from 2.7):

>>> '{0:,.2f}'.format(123466666)
'123,466,666.00'

See http://www.python.org/dev/peps/pep-0378/ for the specification.

like image 155
Theuni Avatar answered Oct 30 '22 09:10

Theuni


Use the locale modules format function:

>>> locale.setlocale(locale.LC_ALL, 'English')
>>> 'English_United States.1252'

>>> print locale.format('%.2f', 123456789.0, True)
>>> 123,456,789.00
like image 39
Björn Lindqvist Avatar answered Oct 30 '22 10:10

Björn Lindqvist