How to round a integer to the close hundred?

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

    I know this is an old thread. I wrote a new method. Hope this will be useful for some one.

        public static double Round(this float value, int precision)
        {
            if (precision < -4 && precision > 15)
                throw new ArgumentOutOfRangeException("precision", "Must be and integer between -4 and 15");
    
            if (precision >= 0) return Math.Round(value, precision);
            else
            {
                precision = (int)Math.Pow(10, Math.Abs(precision));
                value = value + (5 * precision / 10);
                return Math.Round(value - (value % precision), 0);
            }
        }
    

    Example:

    float value = F6666.677777;
    Console.Write(value.Round(2)) // = 6666.68
    Console.Write(value.Round(0)) // = 6667
    Console.Write(value.Round(-2)) // = 6700 
    

提交回复
热议问题