You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python小费计算器:如何让整数结果以两位小数格式打印?

解决小费计算器小数位数问题

问题出在输出时未指定固定小数格式,Python浮点数默认会省略末尾的零。只需修改print语句的格式化逻辑即可解决:

修改后的代码

print("Welcome to the tip calculator")
bill = float(input("What was the total bill? "))
tip = input("What percentage tip would you like to give? 10, 12, or 15? ")
people = input("How many people to split the bill? ")
bill_pp = bill / float(people)  # 简化不必要的重复float转换
bill_pp_wtip = bill_pp * (1 + float(tip)/100)
print(f"Each person should pay: ${bill_pp_wtip:.2f}")

关键修改说明

  • 在f-string中使用: .2f格式说明符(冒号后无空格),强制将数值格式化为两位小数,无论计算结果是整数还是带小数的数,都会显示如10.00的标准格式。
  • 清理了代码中重复的float()转换,让代码更简洁易读。

内容的提问来源于stack exchange,提问作者maestrojimbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:40:27