2014-03-07 85 views
0
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。在Python中舍入百分比

+0

你可以使用:math.ceil 在这里看到:http://stackoverflow.com/questions/4518641/how-to-round-off-a-floating-number-in-python – nvg58

+0

当心:一浮点数不能精确地表示值82.1。最接近的是82.099999999999994315658113919198513031005859375。不过,它在打印时仍然会显示为82.1。 – Kevin

回答

2

您可以使用模板字符串像这样和{0:.1f}手段,第一个参数必须被格式化为带1位小数位数

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

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

round(percentage_blocked,1) 
0

替代解决方案。

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

计算时舍入。 int(x+0.5) x舍正确

0

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

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

注意:没有* 100