round down to 2 decimal in python

后端 未结 5 1403
我寻月下人不归
我寻月下人不归 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:23

    here's a simple function that isn't affected by float precision errors

    def truncate_float(n, places):
        return int(n * (10 ** places)) / 10 ** places
    

    Tests:

    >>> truncate_float(28.266, 3)
    28.266
    >>> truncate_float(28.266, 2)
    28.26
    >>> truncate_float(28.266, 1)
    28.2
    

提交回复
热议问题