This is a Fahrenheit to Celsius conversion. I have it set to 2 decimal points as the output but lets say a user enters 50, it will come out as 10.00. How can I get it to come out as 10 without decimal, but allow decimal when it isn't a whole number?
temp = float(input(" Fahrenheit temperature: "))
celsius = float((5/9)*(temp - 32))
print("The temperature in celsius is: {:.2f}°.".format(celsius))
You can try something like this:
temp = float(input(" Fahrenheit temperature: "))
celsius = float((5/9)*(temp - 32))
if (celsius % 1 == 0):
print("The temperature in celsius is: {}°.".format(celsius))
else:
print("The temperature in celsius is: {:.2f}°.".format(celsius))
The if
condition checks whether or not you have a whole number.
You need to do this separately, because what counts as "close enough" to 50 to display as 50 is application-specific.
if abs(celsius % 1) < 0.001 # Or whatever threshold you want:
print("The temperature in celsius is: {:d}°.".format(int(celsius//1)))
else:
print("The temperature in celsius is: {:.2f}°.".format(celsius))
Try This:
def doTheThing(number):
numString = str(number)
i = len(numString) -1
while True:
if numString[i] == ".":
numString = numString[:-1] #remove the .
break
if numString[i] == "0":
numString = numString[:-1] #remove the 0
else:
break
i-=1
print(numString)
x = 10.0
doTheThing(x)
This will print 10, where as regular print will return 10.0
There is probably a better way but this works ;)
您可以在打印时尝试将摄氏度转换为整数:
print("The temperature in celsius is :{:.2f}°.".format(int(celsius)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.