【问题标题】:Math.Round for decimal in C# [duplicate]C# 中小数的 Math.Round [重复]
【发布时间】:2011-05-27 00:18:17
【问题描述】:

可能重复:
Why does .NET use banker's rounding as default?

这是一个示例代码

decimal num1=390, num2=60, result;
result=num1/num2; // here I get 6.5
result=Math.Round(result,0);

结果的最终值应该是 7,但我得到的是 6。为什么会有这样的行为?

【问题讨论】:

    标签: c# .net math


    【解决方案1】:

    检查第三个参数MidpointRounding

    默认使用 MidpointRounding.ToEven,所以

    Math.Round(result,0); // 6.0 
    //or
    Math.Round(result,0, MidpointRounding.ToEven); // 6.0 
    
    //But:
    Math.Round(result,0, MidpointRounding.AwayFromZero); // 7.0 
    

    【讨论】:

      【解决方案2】:

      来自MSDN

      如果 d 的小数部分是 在两个整数之间,其中之一 一个是偶数,另一个是奇数, 返回偶数。

      【讨论】:

        【解决方案3】:

        这种四舍五入有时称为四舍五入或银行家四舍五入。它可以最大限度地减少由于在单个方向上持续舍入中点值而导致的舍入误差。

        http://msdn.microsoft.com/en-us/library/3s2d3xkk.aspx

        例子:

        //       11.1 --> 11
        //       11.2 --> 11
        //       11.3 --> 11
        //       11.4 --> 11
        //       11.5 --> 11
        //       11.6 --> 12
        

        【讨论】:

          【解决方案4】:

          decimal.Math.Round 默认使用 MidpointRounding.ToEven。

          意思是如果一个人的数字是奇数,它会变成偶数。否则,它保持不变。此行为遵循 IEEE 标准 754 第 4 节。有时称为四舍五入或银行家四舍五入。它可以最大限度地减少由于在单个方向上持续舍入中点值而导致的舍入误差。

          【解决方案5】:

          一定是同一个原因

                Math.Round(6.5, 0);
          

          类似地产生 6 而不是 7。这一切都归结为 MSDN 文档link text 举例说明

            Console.WriteLine(Math.Round(3.45, 1)); //Returns 3.4.
            Console.WriteLine(Math.Round(4.35, 1)); // Returns 4.4
          

          another MDSN Doc是状态

          最接近的整数参数 d。如果 d 的小数部分介于两个整数之间,其中一个为偶数,另一个为奇数,则返回偶数。请注意,此方法返回 Decimal 而不是整数类型。

          【讨论】:

            【解决方案6】:

            使用 Math.Ceiling Method()。 十进制 num1=390, num2=60, 结果;
            结果=Math.Ceiling(num1/num2);

            【讨论】:

            • 不等于四舍五入,5.4 -> 6 而不是 5。
            猜你喜欢
            • 2019-06-11
            • 1970-01-01
            • 1970-01-01
            • 2020-07-24
            • 1970-01-01
            • 1970-01-01
            • 2018-05-12
            • 2011-11-03
            • 1970-01-01
            相关资源
            最近更新 更多