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
So much ugliness out there…
My personal favorite is to convert float
s 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.
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 .
from decimal import Decimal
'%g' % (Decimal(str(x)))
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
>>> '%g' % 0
'0'
>>> '%g' % 0.0
'0'
>>> '%g' % 0.1
'0.1'
>>> '%g' % 1.0
'1'
>>> x = '1.0'
>>> int(float(x))
1
>>> x = 1
>>> int(float(x))
1