【问题标题】:In Python 3, how do I round a floating point number up to a certain decimal place?在 Python 3 中,如何将浮点数四舍五入到某个小数位?
【发布时间】:2019-04-29 17:58:05
【问题描述】:

我有 12.5,我想将其转换为 13。如何在 Python 3 中执行此操作?

任务是这样的 - “给定餐费(餐费的基本成本)、小费百分比(作为小费添加的餐费百分比)和税费百分比(添加为小费的餐费百分比)税)为一顿饭,查找并打印这顿饭的总成本”

我在 Python 3 和 3 个测试用例中解决了这个问题,它表明我的代码正在运行。但有一种情况并非如此。

在哪里,

示例输入:

12.00

20

8

预期输出:

13

我的输出是 12.5

我怎么能把 12.5 当作 13?

mealcost = float(input()) 
tippercent = float(input()) 
taxpercent = float(input())  

tippercent = mealcost * (tippercent / 100)  
taxpercent = mealcost * (taxpercent / 100) 

totalcost = float( mealcost + tippercent + taxpercent)  
print(totalcost)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

使用round()

print(round(12.5))
>>> 13.0

【讨论】:

【解决方案2】:

四舍五入到最接近的 X(即最接近的 20.0)

  1. 只需除以您要四舍五入的值
  2. 然后round结果
  3. 然后将它乘以要四舍五入的数字并转换为整数

例如

round_to_nearest = 20
for a_num in [9,15,22,32,35,66,98]:
    rounded = int(round(a_num/round_to_nearest)*round_to_nearest)
    print("{a_num} rounded = ".format(a_num=a_num,r=rounded))

只是四舍五入

哦,没关系,看起来你只是想要

print(round(12.3),round(12.6)) # 12, 13

如果round 舍入错误(即round(12.5) => 12 in python3),您只需将0.5 加到您的号码上并下限

int(12.5+0.5)

【讨论】:

  • Round() 完成所有这些操作,无需您输入太多内容
  • OP 没有提到四舍五入到最接近的 20。阅读问题的标题。
  • 最近的 20 个?!?!?
  • 只是round(12.5)
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
相关资源
最近更新 更多