Formatting floats without trailing zeros

后端 未结 18 1913
再見小時候
再見小時候 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:31

    Here's the answer:

    import numpy
    
    num1 = 3.1400
    num2 = 3.000
    numpy.format_float_positional(num1, 3, trim='-')
    numpy.format_float_positional(num2, 3, trim='-')
    

    output "3.14" and "3"

    trim='-' removes both the trailing zero's, and the decimal.

提交回复
热议问题