使用float- python将整数舍入



下面是我的代码。问题在MAIN。当一个人试图将商品放入购物车时,代码就会起作用,您可以看到这些商品的总价。他们必须输入他们想要的每件商品的价格。如果一个人输入一个数字到小数点后两位,它会将其四舍五入到最接近的整数。

import locale
class CashRegister:
def __init__(self):
mself.items = 0
self.price = int(float(0.00))


def addItems(self,price): #keeps track of total number of items in cart
self.price += price
self.items += 1
print(self.price)

def getTotal(self):  #returns total price
return self.price

def getCount(self):  #return the item count of the cart
return self.items

def clearCart(self):  #clears cart for another user or checkout
self.items = 0
self.price = int(float(0.00))
def main(): 
user_name = input('What is your name?n') #weclomes user
print("Hello",user_name)
locale.setlocale(locale.LC_ALL, 'en_US')
user_name = CashRegister()  #user is using the cash register
while True:
line = input ("Would you like to add another food item to your cart? Choose y or n n") 
if line  == "y":
**          price = int(float(input("please input the price of the itemn")))
print(price)**
user_name.addItems(price)   #user adds prices to cart
elif line == "n":
print("Your total checkout price:", locale.currency(user_name.getTotal()) )
# int(float(locale.currency(user_name.getTotal())))
print("Your total item count", user_name.getCount())
user_name.clearCart() #clears cart for another user/checkout
break
else:
print("Error")
if __name__ == '__main__':
main()

这个人一输入号码,我就把它打印出来,看看问题是否出在那里。我输入3.20,但它会自动转换为3。我不知道怎么让它保留这些小数。我甚至试着用int/float打印它,它仍然不工作。

int()函数总是返回一个整数。整数有任何小数点。所以只使用

float(input("please input the price of the itemn"))

不是

int(float(input("please input the price of the itemn")))

最新更新