formatting long numbers as strings in python

后端 未结 9 2506
轻奢々
轻奢々 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:36

    Variable precision and no 999999 bug:

    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])
    

提交回复
热议问题