zoukankan      html  css  js  c++  java
  • C#四舍五入说明

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

    string.Format("{0:N2}", d) 与 RoundChinese(d, 2).ToString() 总是相等

            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);
            }
        
  • 相关阅读:
    webstorm配置github 以及本地代码上传github。
    日期控件------moment.js
    图片查看器
    日期
    配置一个node服务器
    git代码管理
    vue
    javascript (字符串, 数组, 对象 , 日期 和 操作元素节点 动画 定时器)
    html css
    JS常用方法
  • 原文地址:https://www.cnblogs.com/tianxue/p/9084443.html
Copyright © 2011-2022 走看看