为数字添加“十进制标记”千分位分隔符
我想知道怎么把数字 1000000
格式化成 1.000.000
这种样子,在这里,'.' 是用来分隔千位的符号。
9 个回答
21
这里稍微扩展一下答案 :)
我需要在数字中添加千位分隔符,同时限制浮点数的精度。
可以通过使用以下格式字符串来实现:
> my_float = 123456789.123456789
> "{:0,.2f}".format(my_float)
'123,456,789.12'
这段内容描述了 format()
函数的格式说明符的小语言:
[[fill]align][sign][#][0][width][,][.precision][type]
来源: https://www.python.org/dev/peps/pep-0378/#current-version-of-the-mini-language
22
要把数字 1123000
格式化成 1,123,000
的样子,可以使用 format
函数:
比如:
>>> format(1123000,',d')
'1,123,000'
另外,你可以查看这个链接了解更多信息: https://docs.python.org/release/3.11.0/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator
117
如果你想在数字中添加千位分隔符,可以这样写:
>>> '{0:,}'.format(1000000)
'1,000,000'
不过这个方法只适用于Python 2.7及以上版本。
你可以查看格式字符串的语法了解更多信息。
在旧版本中,你可以使用locale.format():
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_AU.utf8'
>>> locale.format('%d', 1000000, 1)
'1,000,000'
使用locale.format()
的好处是,它会根据你所在地区的习惯来添加千位分隔符,比如:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')
'de_DE.utf-8'
>>> locale.format('%d', 1000000, 1)
'1.000.000'