代码之家  ›  专栏  ›  技术社区  ›  July

如何定义数字间隔,然后四舍五入

  •  0
  • July  · 技术社区  · 1 年前

    我开始尝试

    (date.minute + 1) % 5
    

    后来,我发现date.minute不一定是连续的。03分钟后,不一定是04分钟。它可能直接跳到06分钟。

    所以我需要被5整除作为区间,然后向上计数。

    例如,如果间隔为5,则将6替换为5,将9替换为5、将10替换为10、将14替换为10。

    2 回复  |  直到 1 年前
        1
  •  1
  •   Sash Sinha    1 年前

    尝试使用楼层划分,即。, // 5 :

    >>> testcases = [6, 9, 10, 14]
    >>> for tc in testcases:
    ...     print(f'{tc} -> {tc // 5 * 5}')
    ... 
    6 -> 5
    9 -> 5
    10 -> 10
    14 -> 10
    
        2
  •  1
  •   Mark    1 年前
    import math
        
    x = math.floor(date.minute * 0.2) * 5
    

    或同样使用整数除法 (date.minute // 5) * 5