formatting long numbers as strings in python

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

    I needed this function today, refreshed the accepted answer a bit for people with 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)

提交回复
热议问题