formatting long numbers as strings in python

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

    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.

    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'
    

提交回复
热议问题