Blog

Filter posts by Category Or Tag of the Blog section!

Round Down and Round Up in C#

Saturday, 19 July 2014

I wonder why there is no method in .Net framework for rounding decimal values as up or down, I've written an extension method for decimal, hope it is helpful for you!

  

 public static class Helper

    {

        public static decimal RoundUp(this decimal number, int places)

        {

            decimal factor = RoundFactor(places);

            number *= factor;

            number = Math.Ceiling(number);

            number /= factor;

            return number;

        }

        public static decimal RoundDown(this decimal number, int places)

        {

            decimal factor = RoundFactor(places);

            number *= factor;

            number = Math.Floor(number);

            number /= factor;

            return number;

        }

        internal static decimal RoundFactor(int places)

        {

            decimal factor = 1m;

            if (places < 0)

            {

                places = -places;

                for (int i = 0; i < places; i++)

                    factor /= 10m;

            }

            else

            {

                for (int i = 0; i < places; i++)

                    factor *= 10m;

            }

            return factor;

        }

}

 

Category: Software

Tags: C#

comments powered by Disqus