formatting long numbers as strings in python

后端 未结 9 2504
轻奢々
轻奢々 2020-11-28 07:00

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?

I\'d li

9条回答
  •  星月不相逢
    2020-11-28 07:38

    A more "math-y" solution is to use 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'
    

提交回复
热议问题