How to turn a float number like 293.4662543 into 293.47 in python?

前端 未结 8 1921
小蘑菇
小蘑菇 2021-01-01 10:19

How to shorten the float result I got? I only need 2 digits after the dot. Sorry I really don\'t know how to explain this better in English...

Thanks

8条回答
  •  清酒与你
    2021-01-01 11:03

    If you need numbers like 2.3k or 12M, this function does the job:

    def get_shortened_integer(number_to_shorten):
        """ Takes integer and returns a formatted string """
        trailing_zeros = floor(log10(abs(number_to_shorten)))
        if trailing_zeros < 3:
            # Ignore everything below 1000
            return trailing_zeros
        elif 3 <= trailing_zeros <= 5:
            # Truncate thousands, e.g. 1.3k
            return str(round(number_to_shorten/(10**3), 1)) + 'k'
        elif 6 <= trailing_zeros <= 8:
            # Truncate millions like 3.2M
            return str(round(number_to_shorten/(10**6), 1)) + 'M'
        else:
            raise ValueError('Values larger or equal to a billion not supported')
    

    Results:

    >>> get_shortened_integer(2300)
    2.3k # <-- str
    
    >>> get_shortened_integer(1300000)
    1.3M # <-- str
    

提交回复
热议问题