在Python3中,如何将浮点数舍入到某个小数位?

2024-03-28 14:07:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有12.5,我想把它转换成13。在python3中如何实现这一点?你知道吗

任务是这样的-“给定一顿饭的价格(一顿饭的基本成本)、小费百分比(加在小费上的饭菜价格的百分比)和税百分比(加在税上的饭菜价格的百分比),找到并打印这顿饭的总成本”

我用python3解决了这个问题,在3个测试用例中,它显示了我的代码正在工作。但有一种情况并非如此。你知道吗

在哪里

样本输入:

12点

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)

Tags: 代码input测试用例价格floatpython3成本百分比
2条回答

使用round()

print(round(12.5))
>>> 13.0

四舍五入到最接近的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)

相关问题 更多 >