How to round a integer to the close hundred?

前端 未结 9 1188
生来不讨喜
生来不讨喜 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:49

    I wrote a simple extension method to generalize this kind of rounding a while ago:

    public static class MathExtensions
    {
        public static int Round(this int i, int nearest)
        {
            if (nearest <= 0 || nearest % 10 != 0)
                throw new ArgumentOutOfRangeException("nearest", "Must round to a positive multiple of 10");
    
            return (i + 5 * nearest / 10) / nearest * nearest;
        }
    }
    

    It leverages integer division to find the closest rounding.

    Example use:

    int example = 152;
    Console.WriteLine(example.Round(100)); // round to the nearest 100
    Console.WriteLine(example.Round(10)); // round to the nearest 10
    

    And in your example:

    Console.WriteLine(76.Round(100)); // 100
    Console.WriteLine(121.Round(100)); // 100
    Console.WriteLine(9660.Round(100)); // 9700
    

提交回复
热议问题