语言环境感知方法,用逗号和小数打印大量数字

时间:2019-01-02 23:02:18

标签: python printing

关于如何用逗号和/或小数位打印数字有很多公认的答案,例如hereherehere等。

由于某种原因,我无法找到一种清晰的答案,即如何以语言环境感知的方式对带有小数的大数执行此操作,而这不会迫使我对精度进行硬编码(例如,当读取文件并从中打印值时它,没有数字的先验知识。

为了使事情变得更复杂,我还希望以Python 2.7 / 3.x交叉兼容的方式进行操作。

因此,如果我有一个诸如1000000.01之类的数字,我希望它显示为“ 1,000,000.01”,而1000000.00001显示为“ 1,000,000.00001”。

这是我尝试过的不起作用的方法:

(使用标准string formatter

# https://docs.python.org/2.7/library/string.html#format-specification-mini-language
x = 1000000.01
print("{:n}".format(x)) # 1e+06 ; locale-aware but doesn't work?
print("{:g}".format(x)) # 1e+06 ; doesn't work
print("{:f}".format(x)) # 1000000.010000 ; wrong number of decimal places
print("{:,}".format(x)) # 1,000,000.01 ; desired result but not locale-aware (?)

根据文档,"{:n}"听起来像我想要的,但似乎没有实际作用。 "{:,}"可以达到预期的效果,但似乎不支持区域设置(根据列出的文档;需要对此进行说明)。

(使用locale library

# https://docs.python.org/2/library/locale.html
import locale
locale.setlocale(locale.LC_ALL, '')
print(locale.format("%g", x, grouping = True)) # 1e+06 ; doesn't work
print(locale.format("%d", x, grouping = True)) # 1,000,000 ; loses decimal place
# print(locale.format("%n", x, grouping = True)) # ValueError: format() must be given exactly one %char format specifier, '%n' not valid
# print(locale.format("{:n}", x, grouping = True)) # ValueError: format() must be given exactly one %char format specifier, '{:n}' not valid

print(locale.format_string("%g", x, grouping = True)) # 1e+06 ; doesn't work
# print(locale.format_string("%n", x, grouping = True)) # TypeError: not enough arguments for format string
print(locale.format_string("{:n}", x, grouping = True)) # {:n} ; not a valid formatter ?

似乎locale.format("%g", ...)与我想要的最接近,但似乎无法正常工作:

print(locale.format("%g", 1000.01, grouping = True)) # 1,000.01 ; works but only for small numbers
print(locale.format("%g", 10000.01, grouping = True)) # 10,000 ; doesn't work, loses decimal

似乎n中缺少local.format格式化程序。

有什么想法吗?似乎真的很奇怪,至少到目前为止我还没有找到通用的建立方法。

1 个答案:

答案 0 :(得分:0)

我的意思是,您可以在小数点处分割并分别计算。可能不理想,但是可以。

# `input` is your number, `output` is the formatted string.
import locale #import
sep = '.' if locale.localeconv()['thousands_sep'] == ',' else ',' #get locale sep
parts = str(input).split(sep) #get part before and after the sep
parts[0] = locale.format("%d", parts[0], grouping=True) #format **part 0**
output = sep.join(parts) #rejoin

我认为这可以做到。

这里重要的部分是对locale.localeconv()['thousands_sep']的调用,该调用获取值分隔符。然后,在同一行上将其反转,以使逗号成为句号,反之亦然。