Thousand separator in format string with floats

formatting, python, python-2.6

Solution

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

Problem

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?

Original source