如何在当前区域设置中格式化 Python 中的浮点数



我想根据当前语言环境在我的 Python 应用程序中格式化浮点数。格式规范迷你语言指出,"浮点和十进制值的可用表示类型"之一是:

"n"号。这与"g"相同,只是它使用当前区域设置插入适当的数字分隔符字符。

但我无法让它工作。这就是我尝试的方式:

$ unset LC_ALL
$ unset LANG
$ export LANG=de_DE.UTF-8
$ python3 -c "import locale; print (locale.getdefaultlocale())"
('de_DE', 'UTF-8')
$ python3 -c "print ('{0:.3n}'.format(3.14))"
3.14

我还尝试过:

$ python3 -c "import locale; print (locale.str(3.14))"
3.14
$ python3 -c "import locale; print (locale.format_string('%.2f', 3.14))"
3.14

我希望所有这些都能打印3,14,而不是3.14.知道出了什么问题吗?

仅设置环境变量是不够的:

$ unset LC_ALL
$ unset LANG
$ export LANG=de_DE.UTF-8

您需要在 Python 脚本的开头使用 locale.setlocale 显式设置LC_NUMERIC或LC_ALL:

$ python3 -c "import locale; locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3.14 3.14 3.14 3.14 3.14
$ python3 -c "import locale; locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3,14 3,14 3,14 3.14 3,14
$ python3 -c "import locale; locale.setlocale(locale.LC_ALL, 'en_US.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3.14 3.14 3.14 3.14 3.14
$ python3 -c "import locale; locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8'); print(locale.str(3.14), '{0:.3n}'.format(3.14), locale.format_string('%.2f', 3.14), '{0:.3g}'.format(3.14), locale.format_string('%.2f', 3.14))"
3,14 3,14 3,14 3.14 3,14

format_string()说"根据当前LC_NUMERIC设置格式化数字值"。

如果要测试不同区域设置中的数字,请按以下方式更改区域设置:

import locale
# Change to German locale
locale.setlocale(locale.LC_NUMERIC, 'de_DE')

使用您的一些示例,我们有:

number = 3.14
print(r'Expecting 3,14   Using %g')
print(locale.format_string('%g', number))
print(r'Expecting 3,14   Using %.2f')
print(locale.format_string('%.2f', number))
print(r'Expecting 3,14   Using locale.str()')
print(locale.str(number))

输出:

Expecting 3,14   Using %g
3,14
Expecting 3,14   Using %.2f
3,14
Expecting 3,14   Using locale.str()
3,14

将区域设置(返回(更改为美国

locale.setlocale(locale.LC_NUMERIC, 'en_US')

现在我得到以下输出:

Expecting 3.14   Using %g
3.14
Expecting 3.14   Using %.2f
3.14
Expecting 3.14   Using locale.str()
3.14

最新更新