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);
            }
        
  • 相关阅读:
    c# 一段生成6位不重复的随机数字码存8万个
    element ui 踩坑记
    Vue node.js 踩坑记
    javascript 异步回调链式调用 promise
    css 盒模型
    vue node.js 引入 linq
    Vue VsCode 项目 launch.json 文件
    node.js 基本语法识记
    Vue 2.0 入门示例识记
    在Windows系统中建立一个隐藏的帐户(在不登录界面显示)
  • 原文地址:https://www.cnblogs.com/tianxue/p/9084443.html
Copyright © 2011-2022 走看看