Search code examples
pythonroundingrounding-error

How to round float numbers in Python?


I know there are different questions like this; and I searched my question on stackoverflow and many other webs, and basically the easiest way to do this is using the round/2 function, but the round function didn't work properly... Here's part of my code using the round function:

ad=150
ad_percent = 75
ap=150
ap_percent=55
armor_pen=35
enemy_armor=125
enemy_max_hp=1000

ap = ap_percent * ap / 100
ad = ad_percent * ad / 100

armor_less = armor_pen * enemy_armor / 100
enemy_armor = enemy_armor - armor_less
# Till now, all is good.

round(ad)
print(ad)

Output

112.5

So... It's not working. How can I make that variable round to 113?

Thanks for helping.


Solution

  • round() returns the rounded value; it doesn't modify its argument (indeed, it couldn't, in Python's data model (unless __round__ on a custom object had been modified to mutate the object itself, but that would be very, very icky, and I digress)).

    You'll need to assign the return value of round(), in other words e.g.

    ad = round(ad)
    

    instead.