【问题标题】:How many digits are used to arrive at Math.Round answer?Math.Round 使用多少位数得出答案?
【发布时间】:2013-02-05 08:28:03
【问题描述】:

在使用 Math.Round 时,在进行“四舍五入”时是否考虑所有小数位,还是只考虑我们要四舍五入到的小数位右侧的数字?

示例;

decimal myNumber1 = 0.2651m;
decimal myNumber2 = 0.2650m;

Math.Round(myNumber1, 2) gives 0.27
Math.Round(myNumber2, 2) gives 0.26

我希望两者都是 0.26,因为四舍五入不考虑小数点后 4 位。

【问题讨论】:

  • the documentation中的备注中指定的内容有什么问题?
  • 感谢您的澄清。我错误地假设当将 0.2651 舍入到小数点后 2 位时,第 3 位将是唯一使用的位。我现在明白,当文档说“右边的值”时,它并不是指“5”,而是“51”或“510000001”等,这显然超出了 5 和 5+1 的中点

标签: c# .net


【解决方案1】:

四舍五入不考虑小数点后四位

这不是真的。

根据 MSDN,Math.Round(decimal) 使用 MidpointRounding.ToEven 的舍入类型。

中点舍入指定当要舍入的值正好在两个可能舍入值的中间时的舍入行为。

例如,

  • 0.2649 将始终舍入为 0.26
  • 0.2651 将始终舍入为 0.27

当四舍五入到小数点后。

有趣的是在0.2650 的情况下会发生什么:默认情况下,使用MidpointRounding.ToEven 你会得到:

  • 0.26Math.Round(0.2650, 2)
  • 0.28Math.Round(0.2750, 2)

这是因为舍入是在舍入后向偶数最高位进行的(第一种情况是6,第二种情况是8)。

但是,如果您使用 MidpointRounding.AwayFromZero,您会得到:

  • 0.27Math.Round(0.2650, 2, MidpointRounding.AwayFromZero)
  • 0.28Math.Round(0.2750, 2, MidpointRounding.AwayFromZero)

【讨论】:

  • 嗯,ToEven 表示x.50000 将四舍五入为x如果是偶数。如果x 是奇数,结果将是x+1
【解决方案2】:

考虑所有小数位。 四舍五入 0.2650000001m 也会得到 0.27

【讨论】:

    【解决方案3】:

    如果您不想要第 4 位十进制数字,则只需在四舍五入前使用 Math.Truncate

    Math.Truncate(0.2651m * 1000) / 1000; //0.265
    Math.Truncate(0.2650m * 1000) / 1000; //0.265
    

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多