Decimal type intercepts and retains N decimal places and rounds up, Decimal type intercepts and retains N decimal places and does not perform rounding operations

Decimal type interception retains N decimal places,
Decimal type interception retains N decimal places and no rounding operation is performed

    
    public class DecimalHelper
    {
        /// <summary>
        /// Decimal type interception retains N decimal places and does not perform rounding operations
        /// </summary>
        /// <param name="d"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static decimal CutDecimalWithN(decimal d, int n)
        {
            string strDecimal = d.ToString();
            int index = strDecimal.IndexOf(".");
            if (index == -1 || strDecimal.Length < index + n + 1)
            {
                strDecimal = string.Format("{0:F" + n + "}", d);
            }
            else
            {
                int length = index;
                if (n != 0)
                {
                    length = index + n + 1;
                }
                strDecimal = strDecimal.Substring(0, length);
            }
            return Decimal.Parse(strDecimal);
        }

        /// <summary>
        /// Decimal type interception retains N decimal places and takes it upwards
        /// </summary>
        /// <param name="d"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static decimal Ceiling(decimal d, int n)
        {
            decimal t = decimal.Parse(Math.Pow(10, n).ToString());
            d = Math.Ceiling(t * d);
            return d / t;
        }
    }

test:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine();
            decimal Dec = 12.12345M;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine($"{Dec} keep {i} decimal places without rounding: " + DecimalHelper.CutDecimalWithN(Dec, i));
            }
            Console.WriteLine();
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine($"{Dec} preserves {i} decimal places for rounding up operation: " + DecimalHelper.Ceiling(Dec, i));
            }
            Console.Read();
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325131293&siteId=291194637