Python咖啡商店代码总价无法保留两位小数的技术咨询
解决Python咖啡师代码中总价两位小数显示问题
你运行的咖啡师代码里,计算出的总价无法以两位小数(末尾补零)的形式显示,比如总价为2.5时会显示成2.5而非2.50,以下是几种简单直接的解决方案:
问题根源
原代码中直接用str(total)转换计算结果,浮点数的字符串转换会自动省略末尾无意义的零,导致无法满足两位小数的显示要求。
解决方案
方法一:使用f-string格式化(Python 3.6+推荐)
修改输出总价的print语句,用f-string的格式说明符强制保留两位小数:
print(f"Thank you. Your total of {quantity} {order} will be €{total:.2f}")
:.2f表示将浮点数格式化为固定两位小数的字符串,不管数值原本的小数位数,都会自动补零到两位。
方法二:使用format()函数
如果习惯用format()函数,可按如下方式修改:
print("Thank you. Your total of {} {} will be €{:.2f}".format(quantity, order, total))
注意:原代码中错误地将完整字符串传入format()函数,这是无效用法,正确方式是在字符串中放置占位符{},再传入对应参数。
方法三:先四舍五入再格式化
如果需要先确保数值精度,可先用round()函数将总价四舍五入到两位小数,再格式化显示:
total_rounded = round(total, 2) print(f"Thank you. Your total of {quantity} {order} will be €{total_rounded:.2f}")
修改后的完整代码
from time import sleep print("\nHello! Welcome to Star Bucks.") name = input("What is your name?\n") print(f"Hello {name}, thank you so much for coming in today.\n") sleep(2) menu = "Black Coffee, Espresso, Latte, Cappucino" print(f"{name}, what would you like from our menu today? Here is what we are serving.\n{menu}") order = input() price = 2.50 quantity = input(f"How many {order}'s would you like?\n") total = price * float(quantity) # 格式化显示两位小数 print(f"Thank you. Your total of {quantity} {order} will be €{total:.2f}") print(f"\nSounds good {name}, we'll have your {quantity} {order}'s ready for you in a moment.")
内容的提问来源于stack exchange,提问作者mita_maus070
相关产品推荐
相关产品推荐

