Thousand separator in string format with floats

I want to have thousands of delimiters in floats. What am I doing:

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

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

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

The workaround I found is to rotate the float to an integer before forming:

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

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

+6
source share
2 answers

Use the language module format function:

 >>> locale.setlocale(locale.LC_ALL, 'English') >>> 'English_United States.1252' >>> print locale.format('%.2f', 123456789.0, True) >>> 123,456,789.00 
+6
source

The locale parameter is a little ugly, as it is not thread safe and very dependent on what the locale actually does. It may be what you want, but here is the internal version of Python (since version 2.7):

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

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

+6
source

Source: https://habr.com/ru/post/913634/


All Articles