2014-03-07 117 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