我该如何格式化十进制数字,使得 32757121.33
显示为 32.757.121,33
?
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'German')
'German_Germany.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32.757.121,33
你可以将区域设置限制在数字值的显示上(使用locale.format()
,locale.str()
等),而不影响其他区域设置:
>>> locale.setlocale(locale.LC_NUMERIC, 'English')
'English_United States.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32,757,121.33
>>> locale.setlocale(locale.LC_NUMERIC, 'German')
'German_Germany.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32.757.121,33
setlocale()
不是线程安全的,并且在使用较大的多模块程序时存在其他几个问题,因此阅读文档非常重要。在小型程序中,这可能并不那么重要。此外,还有其他语言环境名称,如en_EN
或de_DE
,可能比German
等更通用;尽管我还没有找到允许的语言环境设置列表。 - Tim Pietzcker我找到了另一个解决方案:
'{:,.2f}'.format(num).replace(".","%").replace(",",".").replace("%",",")
(num)
之后的那些废话也能让这个东西运行。 - Brian Leach如果由于某些原因您不能或不想使用 locale
,您也可以使用正则表达式来实现:
import re
def sep(s, thou=",", dec="."):
integer, decimal = s.split(".")
integer = re.sub(r"\B(?=(?:\d{3})+$)", thou, integer)
return integer + dec + decimal
sep()
函数接收一个标准Python浮点数的字符串表示,并将其返回为具有自定义千分位和小数分隔符的字符串。
>>> s = "%.2f" % 32757121.33
>>> sep(s)
'32,757,121.33'
>>> sep(s, thou=".", dec=",")
'32.757.121,33'
\B # Assert that we're not at the start of the number
(?= # Match at a position where it's possible to match...
(?: # the following regex:
\d{3} # 3 digits
)+ # repeated at least once
$ # until the end of the string
) # (thereby ensuring a number of digits divisible by 3
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_GB.UTF-8')
'en_GB.UTF-8'
>>> print(locale.format_string('%.2f', 12742126.15, True))
12,742,126.15
这个示例代码适用于在docker容器中的GB。
FROM python:3.8.2-slim-buster
RUN apt-get update && apt-get install -y locales && \
sed -i -e 's/# en_GB.UTF-8 UTF-8/en_GB.UTF-8 UTF-8/' /etc/locale.gen && \
dpkg-reconfigure --frontend=noninteractive locales
ENV LANG en_GB.UTF-8
ENV LC_ALL en_GB.UTF-8
你可以在终端(Linux发行版)上运行以下命令来查找区域设置:
locale -a
然后会出现完整的区域设置列表:
en_AG.utf8
en_AU.utf8
...
en_GB.utf8
...
我喜欢def sep...
,但它并没有自动找到数字本地格式的问题。如果您不想在报告中添加大量代码,那么这确实是您想要的。
您可以使用g.periodsOrCommas={'thou':'.','dec':','}
,其中g是全局可用区域。
将sep更改为:
def sep(s:str):
thou=g.periodsOrCommas['thou']
dec= g.periodsOrCommas['dec']
然后作为程序设置的一部分,或者向用户进行查询,将句点和逗号设置为所需格式。在所有报告或窗口中,调用sep来处理浮点表示。 最后,您可以在sep中设置选项以指定小数位数,甚至是所需的格式类型。但这远远超出了当前问题的范围。 感谢您提供了一个解决我面临的实际问题的好方法。