dropping trailing '.0' from floats

后端 未结 16 2080
傲寒
傲寒 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'
    
    0 讨论(0)
  • 2020-12-05 04:32

    FWIW, with Jinja2 where var = 10.3

    {{ var|round|int }} will emit integer 10

    round(method='floor') and round(method='ceil') are also available.

    So that were var2 = 10.9 {{ var|round(method='floor')|int }} will still emit integer 10

    Precision can also be controlled using a keyword argument precision=0 of the round function.

    ref: http://jinja.pocoo.org/docs/dev/templates/#round

    0 讨论(0)
  • 2020-12-05 04:32

    Us the 0 prcision and add a period if you want one. EG "%.0f."

    >>> print "%.0f."%1.0
    1.
    >>> 
    
    0 讨论(0)
  • 2020-12-05 04:37

    See PEP 3101:

    'g' - General format. This prints the number as a fixed-point
          number, unless the number is too large, in which case
          it switches to 'e' exponent notation.
    

    Old style (not preferred):

    >>> "%g" % float(10)
    '10'
    

    New style:

    >>> '{0:g}'.format(float(21))
    '21'
    

    New style 3.6+:

    >>> f'{float(21):g}'
    '21'
    
    0 讨论(0)
  • 2020-12-05 04:37

    rstrip doesn't do what you want it to do, it strips any of the characters you give it and not a suffix:

    >>> '30000.0'.rstrip('.0')
    '3'
    

    Actually, just '%g' % i will do what you want. EDIT: as Robert pointed out in his comment this won't work for large numbers since it uses the default precision of %g which is 6 significant digits.

    Since str(i) uses 12 significant digits, I think this will work:

    >>> numbers = [ 0.0, 1.0, 0.1, 123456.7 ]
    >>> ['%.12g' % n for n in numbers]
    ['1', '0', '0.1', '123456.7']
    
    0 讨论(0)
  • 2020-12-05 04:38
    (str(i)[-2:] == '.0' and str(i)[:-2] or str(i) for i in ...)
    
    0 讨论(0)
提交回复
热议问题