千位分隔符格式字符串与浮点数

Clo*_*eto 7 python formatting python-2.6

我想在花车中有千个分隔符.我在做的是:

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

当整数部分有7位或更多位数时,它不起作用:

>>> print '{0:n}'.format(1234567.0)
1.23457e+06
Run Code Online (Sandbox Code Playgroud)

我找到的解决方法是在格式化之前将浮点数转换为整数:

>>> print '{0:n}'.format(int(1234567.0))
1,234,567
Run Code Online (Sandbox Code Playgroud)

是否有一个格式字符串可以处理所有浮点数而无需先将其转换为整数?

The*_*uni 8

语言环境设置有点难看,因为它不是线程安全的,并且非常依赖于语言环境实际执行的操作.它可能是你想要的,但这里是Python的内部版本(从2.7开始):

>>> '{0:,.2f}'.format(123466666)
'123,466,666.00'
Run Code Online (Sandbox Code Playgroud)

有关规范,请参见http://www.python.org/dev/peps/pep-0378/.


Bjö*_*ist 7

使用locale模块格式函数:

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

>>> print locale.format('%.2f', 123456789.0, True)
>>> 123,456,789.00
Run Code Online (Sandbox Code Playgroud)