How to round a integer to the close hundred?

前端 未结 9 1198
生来不讨喜
生来不讨喜 2020-11-29 08:57

I don\'t know it my nomenclature is correct! Anyway, these are the integer I have, for example :

76
121
9660

And I\'d like to round them to

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 09:32

    If you only want to round integer numbers up (as the OP actually did), then you can resort to this solution:

    public static class MathExtensions
    {
        public static int RoundUpTo(this int number, int nearest)
        {
            if (nearest < 10 || nearest % 10 != 0)
                throw new ArgumentOutOfRangeException(nameof(nearest), $"{nameof(nearest)} must be a positive multiple of 10, but you specified {nearest}.");
    
            int modulo = number % nearest;
            return modulo == 0 ? number : modulo > 0 ? number + (nearest - modulo) : number - modulo;
        }
    }
    

    If you want to perform floating-point (or decimal) rounding, then resort to the answers of @krizzzn and @Jim Aho.

提交回复
热议问题