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)

From this I am getting numbers such as 82.113124523242323. How can I round this percentage to the 10th place e.g. 82.1.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user3352353
  • 265
  • 2
  • 3
  • 4
  • you can use: math.ceil See here: http://stackoverflow.com/questions/4518641/how-to-round-off-a-floating-number-in-python – nvg58 Mar 07 '14 at 13:00
  • Beware: a floating point number cannot precisely represent the value 82.1. The closest it can get is 82.099999999999994315658113919198513031005859375. It will still appear as 82.1 when you print it, though. – Kevin Mar 07 '14 at 13:00

5 Answers5

4

I think the standard round function should work

round(percentage_blocked,1)
drmariod
  • 83
  • 5
3

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))
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Note that if you blocked 0.04% of the attack, this will say "You blocked 0.0 percent of the attack". Same with 99.95%, it will say "100.0 percent". – Boris Verkhovskiy Jul 05 '20 at 17:25
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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
1
print("You have blocked %.1f percent of the enemy's attack." % percentage_blocked)
freakish
  • 54,167
  • 9
  • 132
  • 169
0

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

Guy
  • 604
  • 5
  • 21