Python string interpolation: only show necessary decimal places
One option is something like
"{0}\"".format(str(round(x, 1) if x % 1 else int(x)))
which will display x
as an integer if there's no fractional part. There's quite possibly a better way to go about this.
This is reusable, can be used on str
, float
, or int
, and will convert ''
to 0
:
def minimalNumber(x):
if type(x) is str:
if x == '':
x = 0
f = float(x)
if f.is_integer():
return int(f)
else:
return f
Use with:
print "{}\"".format(minimalNumber(x))
Example:
x = 2.2
print "{}\"".format(minimalNumber(x))
x = 2.0
print "{}\"".format(minimalNumber(x))
Which outputs:
2.2"
2"