How to round a integer to the close hundred?

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

    Hi i write this extension this gets the next hundred for each number you pass

    /// 
        /// this extension gets the next hunfìdred for any number you whant
        /// 
        /// numeber to rounded
        /// the next hundred number
        /// 
        /// eg.:
        /// i =   21 gets 100
        /// i =  121 gets 200
        /// i =  200 gets 300
        /// i = 1211 gets 1300
        /// i = -108 gets -200
        /// 
        public static int RoundToNextHundred(this int i)
        {
            return i += (100 * Math.Sign(i) - i % 100);
            //use this line below if you want RoundHundred not NEXT
            //return i % 100 == byte.MinValue? i : i += (100 * Math.Sign(i) - i % 100);
        }
    
        //and for answer at title point use this algoritm
        var closeHundred = Math.Round(number / 100D)*100;
    
        //and here the extension method if you prefer
    
        /// 
        /// this extension gets the close hundred for any number you whant
        /// 
        /// number to be rounded
        /// the close hundred number
        /// 
        /// eg.:
        /// number =   21 gets    0
        /// number =  149 gets  100
        /// number =  151 gets  200
        /// number = -149 gets -100
        /// number = -151 gets -200
        /// 
        public static int RoundCloseHundred(this int number)
        {
            return (int)Math.Round(number / 100D) * 100;
        }
    

提交回复
热议问题