在Python中舍入一个百分比

时间:2014-03-07 12:56:29

标签: python

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。如何将此百分比舍入到第10位,例如82.1。

5 个答案:

答案 0 :(得分:2)

您可以使用这样的模板字符串,{0:.1f}表示第一个参数必须格式化为1个十进制数

print("You have blocked {0:.1f} percent of the enemy's attack.".format(percentage_blocked))

答案 1 :(得分:1)

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

答案 2 :(得分:0)

我认为标准的圆形功能应该起作用

round(percentage_blocked,1)

答案 3 :(得分:0)

替代解决方案。

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

计算时围绕它。 int(x+0.5)正确地围绕x

答案 4 :(得分:0)

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

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

注意:没有* 100