dropping trailing '.0' from floats

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']

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'

>>> x = '1.0'
>>> int(float(x))
1
>>> x = 1
>>> int(float(x))
1

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.

Tags:

Python