.NET method to round a number up to the nearest multiple of another number?

后端 未结 4 911
南笙
南笙 2020-12-31 08:11

I\'m looking for a method that can round a number up to the nearest multiple of another. This is similar Quantization.

Eg. If I want to round 81 up to the

4条回答
  •  温柔的废话
    2020-12-31 08:34

    public static int RoundUp(int num, int multiple)
    {
      if (multiple == 0)
        return 0;
      int add = multiple / Math.Abs(multiple);
      return ((num + multiple - add) / multiple)*multiple;
    }
    
    
    static void Main()
    {
      Console.WriteLine(RoundUp(5, -2));
      Console.WriteLine(RoundUp(5, 2));
    }
    
    /* Output
     * 4
     * 6
    */
    

提交回复
热议问题