【问题标题】:round down numbers to the next 5 in python [duplicate]在python中将数字向下舍入到下一个5 [重复]
【发布时间】:2022-01-25 16:36:45
【问题描述】:

我想在 python 中将数字向下舍入到下一个 5
我的意思:

1 -> 0
3 -> 0
4 -> 0
5 -> 5
7 -> 5
9 -> 5
...

我已经搜索了很多带基数的四舍五入数字,但也搜索了3 -> 5,但它必须是3 -> 0

谢谢你帮我解决这个问题

【问题讨论】:

    标签: python numbers rounding


    【解决方案1】:

    只需将整数除以 5 的余数相减:

    n - n % 5 
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Python 2:

      def func(n):
          return (n / 5) * 5
      

      如果您使用的是 Python 3:

      def func(n):
          return (n // 5) * 5
      

      【讨论】:

        【解决方案3】:

        使用 math.floor 的方式更少 hacky / 更多 Pythonian,如下所示:

        from math import floor
        
        def floor5(x):
          return floor(x/5)*5
        
        # Test:
        print(list(map(floor5, [1, 3, 4, 5, 7, 9])))
        

        输出

        [0, 0, 0, 5, 5, 5]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多