dropping trailing '.0' from floats

后端 未结 16 2078
傲寒
傲寒 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:18

    So much ugliness out there…

    My personal favorite is to convert floats that don't require to be a float (= when they actually are integers) to int, thus removing the, now useless, trailing 0

    (int(i) if i.is_integer() else i for i in lst)

    Then you can print them normally.

    0 讨论(0)
  • 2020-12-05 04:21
    def floatstrip(x):
        if x == int(x):
            return str(int(x))
        else:
            return str(x)
    

    Be aware, though, that Python represents 0.1 as an imprecise float, on my system 0.10000000000000001 .

    0 讨论(0)
  • 2020-12-05 04:24
    from decimal import Decimal
    '%g' % (Decimal(str(x)))
    
    0 讨论(0)
  • 2020-12-05 04:28

    Following code will convert contents of variable no as it is i.e. 45.60. If you use str the output will be 45.6

    no = 45.60
    
    strNo = "%.2f" %no
    
    0 讨论(0)
  • 2020-12-05 04:29
    >>> '%g' % 0
    '0'
    >>> '%g' % 0.0
    '0'
    >>> '%g' % 0.1
    '0.1'
    >>> '%g' % 1.0
    '1'
    
    0 讨论(0)
  • 2020-12-05 04:30
    >>> x = '1.0'
    >>> int(float(x))
    1
    >>> x = 1
    >>> int(float(x))
    1
    
    0 讨论(0)
提交回复
热议问题