我想根据德国编号约定格式化整数和 float 。这可以使用格式语言和表示类型 n
但在我的平台上失败。
(v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] 在 darwin
例子:
1234
=> 1.234
1234.56
=> 1.234,56
1000000
=> 1.000.000
到目前为止我所尝试的:
设置德语语言环境
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
格式规范选项,
只识别英文格式。
'{:,}'.format(1234)
'1,234'
'{:,}'.format(1234.56)
'1,234.56'
'{:,}'.format(1000000)
'1,000,000'
根据Python docs ,整数和浮点表示类型 n
应该做我想做的,但它没有。
'{:n}'.format(1234)
'1234'
'{:n}'.format(1234.56)
'1234,56' # at least the comma was set correctly here
'{:n}'.format(1000000)
'1000000'
'{:n}'.format(12345769.56)
'1,23458e+07' # it's doing weird things for large floats
受@J.F.Sebastian 启发的更多示例和比较:
for n in [1234, 1234.56, 1000000, 12345769.56]:
print('{0:,} {0:n}'.format(n))
fmt, val = "%d %f", (n, n)
print(fmt % val)
print(locale.format_string(fmt, val))
print(locale.format_string(fmt, val, grouping=True))
print('-'*60)
这会在我的平台上产生以下错误结果:
1,234 1234
1234 1234.000000
1234 1234,000000
1234 1234,000000
------------------------------------------------------------
1,234.56 1234,56
1234 1234.560000
1234 1234,560000
1234 1234,560000
------------------------------------------------------------
1,000,000 1000000
1000000 1000000.000000
1000000 1000000,000000
1000000 1000000,000000
------------------------------------------------------------
12,345,769.56 1,23458e+07
12345769 12345769.560000
12345769 12345769,560000
12345769 12345769,560000
------------------------------------------------------------
我没有得到的正确结果如下所示:
1,234 1.234
1234 1234.000000
1234 1234,000000
1.234 1.234,000000
------------------------------------------------------------
1,234.56 1.234,56
1234 1234.560000
1234 1234,560000
1.234 1.234,560000
------------------------------------------------------------
1,000,000 1.000.000
1000000 1000000.000000
1000000 1000000,000000
1.000.000 1.000.000,000000
------------------------------------------------------------
12,345,769.56 1,23458e+07
12345769 12345769.560000
12345769 12345769,560000
12.345.769 12.345.769,560000
------------------------------------------------------------
您有仅使用格式语言的解决方案吗?有什么方法可以欺骗我平台上的区域设置以接受分组?
最佳答案
super 丑陋,但从技术上回答了这个问题:
来自 PEP 378 :
'{:,}'.format(1234.56).replace(",", "X").replace(".", ",").replace("X", ".")
'1.234,56'
https://stackoverflow.com/questions/14287051/