If I have for example x = 40 I want the following result:
40"
For x = 2.5 the result should be like...
2.5"
So I basically want to format to at most one decimal place. I currently use this:
"{0:0.1f}\"".format(x, 1)
But this displays always exactly one decimal place, which is not really what I want...
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"
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.
Maybe not necessarily completely clean solution, but I think at least a little bit more explicit:
"{1:0.{0}f}\"".format(int(not float(x).is_integer()), x)
which may be replaced with more cryptic (based on Michael Mior rounding idea):
"{1:0.{0}f}\"".format(int(x % 1 > 0), x)
if you prefer shorter expressions (less pythonic though).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With