Rounding A Percentage In 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.' % per
Solution 1:
I think the standard round function should work
round(percentage_blocked,1)
Solution 2:
You can use the template string like this and {0:.1f}
means, the first parameter has to be formatted to be with 1 decimal digit
print("You have blocked {0:.1f} percent of the enemy's attack.".format(percentage_blocked))
Solution 3:
You could use {:.1%}
format:
blocked = (enemy_attack - block) / enemy_attack
print("You have blocked {:.1%} percent of the enemy's attack.".format(blocked))
Notice: there is no * 100
.
Solution 4:
print("You have blocked %.1f percent of the enemy's attack." % percentage_blocked)
Solution 5:
Alternate solution.
percentage_blocked = int(
((enemy_attack - block)/(enemy_attack) * 100)*10 + 0.5)/10
Round it while calculating. int(x+0.5)
rounds x properly
Post a Comment for "Rounding A Percentage In Python"