在Python中取整百分比

5
if act == "block" and enemy_decision != 2:
    percentage_blocked = (enemy_attack - block)/(enemy_attack) * 100
    print("You have blocked %s percent of the enemy's attack." % percentage_blocked)

我得到的数字是82.113124523242323。如何将此百分比四舍五入到十分位,例如82.1。


请参考此处:https://dev59.com/yW855IYBdhLWcg3wIAka您可以使用 math.ceil 函数。 - nvg58
注意:浮点数无法精确表示值82.1。它能够接近的最近值是82.099999999999994315658113919198513031005859375。但当你打印输出时,它仍然会显示为82.1。 - Kevin
5个回答

4
我认为标准的round函数应该可以解决问题。
round(percentage_blocked,1)

3
你可以像这样使用模板字符串,{0:.1f} 表示第一个参数需要格式化为带有一位小数的数字。
print("You have blocked {0:.1f} percent of the enemy's attack.".format(percentage_blocked))

请注意,如果您阻止了攻击的0.04%,则会显示“您阻止了攻击的0.0%”。同样,如果是99.95%,则会显示“100.0%”。 - user3064538

3

您可以使用{:.1%}格式:

blocked = (enemy_attack - block) / enemy_attack
print("You have blocked {:.1%} percent of the enemy's attack.".format(blocked))

注意:这里没有* 100


1
print("You have blocked %.1f percent of the enemy's attack." % percentage_blocked)

0

另一种解决方案。

percentage_blocked = int(
           ((enemy_attack - block)/(enemy_attack) * 100)*10 + 0.5)/10

在计算时进行四舍五入。int(x+0.5)可以正确地将x四舍五入。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接