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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With