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

后端 未结 4 804
南笙
南笙 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
    */
    
    0 讨论(0)
  • 2020-12-31 08:37

    If you're using a lot of these on a relatively slow platform, you may eliminate the multiplication by using a variant of:

    t = m + n - 1; return (t - (t % n));

    Of course, if you can limit your multiple to values of 2^n, then the modulus operation may also be deprecated in favour of its logical equivalent (usually "&").

    Incidentally, the "RoundUp" function illustrated above is seriously flawed and will only round down correctly when {(m % n) == (n - 1)}; rounding down is implicit for integer division and as such, does not require compensation.

    0 讨论(0)
  • 2020-12-31 08:41

    Lee's answer is good but it should have been:

    t = m + n - 1; return (t - (t % m));
    

    Notice the change from N to M. The modulo operation should be done with the multiplier (m) and not with the number (n).

    0 讨论(0)
  • 2020-12-31 09:00

    Yes, integer arithmetic.

    To round m up to the next multiple of n, use ((m+n-1)/n)*n

    0 讨论(0)
提交回复
热议问题