round down to 2 decimal in python

后端 未结 5 1410
我寻月下人不归
我寻月下人不归 2020-12-01 18:46

I need to round down and it should be two decimal places.
Tried the following,

a = 28.266
print round(a, 2)

28.27

<
5条回答
  •  暖寄归人
    2020-12-01 19:25

    There's an even simpler way of doing this generically, by subtracting a small quantity before rounding, like so:

    a = 28.269
    digits = 2
    print(round(a - 0.5/10**digits, digits))
    

    This is based on the intuition that one way of rounding a float to the nearest integer is by adding 0.5, then truncating. The above solution does the opposite by subtracting a half of the minimal 'tick' that the desired precision allows, then rounding.

提交回复
热议问题