python 在python中将长数字格式化为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/579310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
formatting long numbers as strings in python
提问by user63503
What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?
Python 中有什么简单的方法可以将整数格式化为字符串,用 K 表示千,用 M 表示百万,并在逗号后只留下几个数字?
I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.
我想将 7436313 显示为 7.44M,将 2345 显示为 2,34K。
Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?
是否有一些 % 字符串格式化运算符可用?或者只能通过在循环中实际除以 1000 并逐步构建结果字符串来完成?
回答by Adam Rosenfield
I don't think there's a built-in function that does that. You'll have to roll your own, e.g.:
我不认为有一个内置函数可以做到这一点。你必须自己动手,例如:
def human_format(num):
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
print('the answer is %s' % human_format(7436313)) # prints 'the answer is 7.44M'
回答by rtaft
This version does not suffer from the bug in the previous answers where 999,999 gives you 1000.0K. It also only allows 3 significant figures and eliminates trailing 0's.
此版本不会受到先前答案中 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])
The output looks like:
输出看起来像:
>>> human_format(999999)
'1M'
>>> human_format(999499)
'999K'
>>> human_format(9994)
'9.99K'
>>> human_format(9900)
'9.9K'
>>> human_format(6543165413)
'6.54B'
回答by manugrandio
A more "math-y" solution is to use math.log
:
更“数学”的解决方案是使用math.log
:
from math import log, floor
def human_format(number):
units = ['', 'K', 'M', 'G', 'T', 'P']
k = 1000.0
magnitude = int(floor(log(number, k)))
return '%.2f%s' % (number / k**magnitude, units[magnitude])
Tests:
测试:
>>> human_format(123456)
'123.46K'
>>> human_format(123456789)
'123.46M'
>>> human_format(1234567890)
'1.23G'
回答by michauwilliam
Variable precision and no 999999 bug:
可变精度且没有 999999 错误:
def human_format(num, round_to=2):
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num = round(num / 1000.0, round_to)
return '{:.{}f}{}'.format(round(num, round_to), round_to, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
回答by Roelant
I needed this function today, refreshed the accepted answer a bit for people with Python >= 3.6:
我今天需要这个函数,为 Python >= 3.6 的人更新了一点接受的答案:
def human_format(num, precision=2, suffixes=['', 'K', 'M', 'G', 'T', 'P']):
m = sum([abs(num/1000.0**x) >= 1 for x in range(1, len(suffixes))])
return f'{num/1000.0**m:.{precision}f}{suffixes[m]}'
print('the answer is %s' % human_format(7454538)) # prints 'the answer is 7.45M'
Edit: given the comments, you might want to change to round(num/1000.0)
编辑:鉴于评论,您可能想要更改为 round(num/1000.0)
回答by Jordi Riera
I had the same need. And if anyone comes on this topic, I found a lib to do so: https://github.com/azaitsev/millify
我有同样的需求。如果有人谈到这个话题,我找到了一个库来这样做:https: //github.com/azaitsev/millify
Hope it helps :)
希望能帮助到你 :)
回答by Blair Conrad
No String Formatting Operator, according to the docs. I've never heard of such a thing, so you may have to roll your own, as you suggest.
根据文档,没有字符串格式操作符。我从来没有听说过这样的事情,所以你可能不得不按照你的建议自己动手。
回答by schnaader
I don't think there are format operators for that, but you can simply divide by 1000 until the result is between 1 and 999 and then use a format string for 2 digits after comma. Unit is a single character (or perhaps a small string) in most cases, which you can store in a string or array and iterate through it after each divide.
我认为没有格式运算符,但您可以简单地除以 1000,直到结果介于 1 和 999 之间,然后在逗号后使用 2 位格式字符串。在大多数情况下,单位是单个字符(或者可能是一个小字符串),您可以将其存储在字符串或数组中,并在每次除法后遍历它。
回答by zweiterlinde
I don't know of any built-in capability like this, but here are a couple of list threads that may help:
我不知道任何像这样的内置功能,但这里有几个列表线程可能会有所帮助:
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2005-09/msg03327.htmlhttp://mail.python.org/pipermail/python-list/2008-August/503417.html
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2005-09/msg03327.html http://mail.python.org/pipermail/python-list/2008-August/503417.html