zoukankan      html  css  js  c++  java
  • Decimal类型截取保留N位小数向上取, Decimal类型截取保留N位小数并且不进行四舍五入操作

    Decimal类型截取保留N位小数向上取
    Decimal类型截取保留N位小数并且不进行四舍五入操作

    封装静态方法

        
        public class DecimalHelper
        {
            /// <summary>
            /// Decimal类型截取保留N位小数并且不进行四舍五入操作
            /// </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类型截取保留N位小数向上取
            /// </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;
            }
        }
    

    测试方法:

        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine();
                decimal Dec = 12.12345M;
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine($"{Dec} 保留{i} 位小数不进行四舍五入操作:" + DecimalHelper.CutDecimalWithN(Dec, i));
                }
                Console.WriteLine();
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine($"{Dec} 保留{i} 位小数向上取整操作:" + DecimalHelper.Ceiling(Dec, i));
                }
                Console.Read();
            }
        }
    

  • 相关阅读:
    Linux network driver
    Linux dd
    Linux aclocal
    Ubuntu
    Makefile
    控制导出符号
    Apache
    Linux nm命令
    Git Submodule
    Linux sed
  • 原文地址:https://www.cnblogs.com/heyangyi/p/8981225.html
Copyright © 2011-2022 走看看