I want python to show only decimal places that are actually necessary. For example :
x = 10
print("The value of 'x' is - " + float(x))
will print only :
The value of 'x' is - 10.0
This is really irritating as I am trying to make a calculator that uses float()
in many places and I just can't seem to get rid of the .0
.
I am looking for a really simplistic code. And, I don't want the number to be rounded in any way such that the original, accurate value is changed.
I am using Anaconda Spyder (Python 3.8) and I will be running the code on Anaconda Prompt.
What about checking if it's a float before printing?
x = 10
y= int(x) if int(x)==x else float(x)
print("The value of 'x' is - " + str(y))
Examples:
x = 10
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10
x = 10.32
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10.32
x = 10.0
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10