dropping trailing '.0' from floats

后端 未结 16 2226
傲寒
傲寒 2020-12-05 03:54

I\'m looking for a way to convert numbers to string format, dropping any redundant \'.0\'

The input data is a mix of floats and strings. Desired output:

0

16条回答
  •  被撕碎了的回忆
    2020-12-05 04:32

    If you only care about 1 decimal place of precision (as in your examples), you can just do:

    ("%.1f" % i).replace(".0", "")
    

    This will convert the number to a string with 1 decimal place and then remove it if it is a zero:

    >>> ("%.1f" % 0).replace(".0", "")
    '0'
    >>> ("%.1f" % 0.0).replace(".0", "")
    '0'
    >>> ("%.1f" % 0.1).replace(".0", "")
    '0.1'
    >>> ("%.1f" % 1.0).replace(".0", "")
    '1'
    >>> ("%.1f" % 3000.0).replace(".0", "")
    '3000'
    >>> ("%.1f" % 1.0000001).replace(".0", "")
    '1'
    

提交回复
热议问题