在 Python 中,有什么简单的方法可以将整数格式化为字符串,用 K 表示千位,用 M 表示百万位,并且在逗号后面只留下几个数字?
我想将 7436313 显示为 7.44M,将 2345 显示为 2,34K。
是否有一些可用的 % 字符串格式化运算符?或者只能在循环中实际除以 1000 并逐步构造结果字符串来完成?
最佳答案
此版本不受先前答案中的错误的影响,即 999,999 为您提供 1000.0K。它还只允许 3 个有效数字并消除尾随的 0。
def human_format(num):
num = float('{:.3g}'.format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])
输出如下:
>>> human_format(999999)
'1M'
>>> human_format(999499)
'999K'
>>> human_format(9994)
'9.99K'
>>> human_format(9900)
'9.9K'
>>> human_format(6543165413)
'6.54B'
https://stackoverflow.com/questions/579310/