简体   繁体   English

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

[英]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: 当整数部分有7位或更多位数时,它不起作用:

>>> 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): 它可能是你想要的,但这里是Python的内部版本(从2.7开始):

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

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

Use the locale modules format function: 使用locale模块格式函数:

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

>>> print locale.format('%.2f', 123456789.0, True)
>>> 123,456,789.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM