Formatting floats without trailing zeros

后端 未结 18 1536
再見小時候
再見小時候 2020-11-22 10:03

How can I format a float so that it doesn\'t contain trailing zeros? In other words, I want the resulting string to be as short as possible.

For example:

<         


        
18条回答
  •  盖世英雄少女心
    2020-11-22 10:33

    For float you could use this:

    def format_float(num):
        return ('%i' if num == int(num) else '%s') % num
    

    Test it:

    >>> format_float(1.00000)
    '1'
    >>> format_float(1.1234567890000000000)
    '1.123456789'
    

    For Decimal see solution here: https://stackoverflow.com/a/42668598/5917543

提交回复
热议问题