This question already has answers here:
Get human readable version of file size? [closed]

(23个答案)



Verbally format a number in Python

(3个答案)


7年前关闭。




是否有一个python库可以使诸如此类的数字更易读

$ 187,280,840,422,780

编辑:例如,此输出为187万亿,而不仅仅是逗号分隔。所以我希望产出是数万亿,数百万,数十亿等

最佳答案

据我了解,您只需要“最重要的”部分。为此,请使用floor(log10(abs(n)))获取数字位数,然后从那里开始。可能是这样的:

import math

millnames = ['',' Thousand',' Million',' Billion',' Trillion']

def millify(n):
    n = float(n)
    millidx = max(0,min(len(millnames)-1,
                        int(math.floor(0 if n == 0 else math.log10(abs(n))/3))))

    return '{:.0f}{}'.format(n / 10**(3 * millidx), millnames[millidx])

为多个不同的数字运行以上函数:
for n in (1.23456789 * 10**r for r in range(-2, 19, 1)):
    print('%20.1f: %20s' % (n,millify(n)))
                 0.0:                    0
                 0.1:                    0
                 1.2:                    1
                12.3:                   12
               123.5:                  123
              1234.6:           1 Thousand
             12345.7:          12 Thousand
            123456.8:         123 Thousand
           1234567.9:            1 Million
          12345678.9:           12 Million
         123456789.0:          123 Million
        1234567890.0:            1 Billion
       12345678900.0:           12 Billion
      123456789000.0:          123 Billion
     1234567890000.0:           1 Trillion
    12345678900000.0:          12 Trillion
   123456789000000.0:         123 Trillion
  1234567890000000.0:        1235 Trillion
 12345678899999998.0:       12346 Trillion
123456788999999984.0:      123457 Trillion
1234567890000000000.0:     1234568 Trillion

08-25 01:09