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

后端 未结 4 908
南笙
南笙 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: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.

提交回复
热议问题