dropping trailing '.0' from floats

Viewed 73509

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

0.0 --> '0'

0.1 --> '0.1'

1.0 --> '1'

I've come up with the following generator expression, but I wonder if there's a faster way:

(str(i).rstrip('.0') if i else '0' for i in lst)

The truth check is there to prevent 0 from becoming an empty string.

EDIT: The more or less acceptable solution I have for now is this:

('%d'%i if i == int(i) else '%s'%i for i in lst)

It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.

17 Answers

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']
>>> x = '1.0'
>>> int(float(x))
1
>>> x = 1
>>> int(float(x))
1
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 .

(str(i)[-2:] == '.0' and str(i)[:-2] or str(i) for i in ...)

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'
from decimal import Decimal
'%g' % (Decimal(str(x)))

Using Python's string formatting (use str.format() with Python 3.0):

from decimal import Decimal

def format_number(i):
    return '%g' % (Decimal(str(i)))
>>> '%g' % 0
'0'
>>> '%g' % 0.0
'0'
>>> '%g' % 0.1
'0.1'
>>> '%g' % 1.0
'1'

I did this for removing trailing nonsignificant digits past a certain precision.

c = lambda x: float(int(x * 100)/100.)
c(0.1234)

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

>>> print "%.0f."%1.0
1.
>>> 
Related