C#四捨五入說明

string.Format("{0:N2}", d) 與 Math.Round(d, 2).ToString() 不老是相等git

string.Format("{0:N2}", d) 與 RoundChinese(d, 2).ToString() 老是相等spa

        private static void TestDisplayDecimal()
        {
            // 結論1:string.Format("{0:N2}", d) 與  Math.Round(d, 2).ToString() 【不老是相等】
            // 結論2:string.Format("{0:N2}", d) 與 RoundChinese(d, 2).ToString() 【老是相等】

            for (var i = 0; i <= 30; i++)
            {
                var d = 2.14M + i / 1000M;
                bool ret = string.Format("{0:N2}", d) == Math.Round(d, 2).ToString();
                if (!ret)
                {
                    Console.WriteLine(d + ":" + string.Format("{0:N2}", d) + "," + Math.Round(d, 2) + "," + ret);
                }
            }

            Console.WriteLine("-----------------------");

            for (var i = 0; i <= 30; i++)
            {
                var d = 2.14M + i / 1000M;
                bool ret = string.Format("{0:N2}", d) == RoundChinese(d, 2).ToString();

                Console.WriteLine(d + ":" + string.Format("{0:N2}", d) + "," + RoundChinese(d, 2).ToString() + "," + ret);
            }
        }

 

 

        /// <summary>
        /// 中國版的四捨五入
        /// </summary>
        /// <param name="value"></param>
        /// <param name="digit"></param>
        /// <returns></returns>
        public static decimal RoundChinese(decimal value, int digit)
        {
            double vt = Math.Pow(10, digit);
            //1.乘以倍數 + 0.5
            decimal vx = value * (decimal)vt + 0.5M;
            //2.向下取整
            decimal temp = Math.Floor(vx);
            //3.再除以倍數
            return (temp / (decimal)vt);
        }
    
相關文章
相關標籤/搜索