gpt4 book ai didi

c# - Math.Round 答案使用多少位数字?

转载 作者:行者123 更新时间:2023-11-30 21:00:50 28 4
gpt4 key购买 nike

使用 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,因为四舍五入不考虑小数点后第四位。

最佳答案

the 4th decimal place is not considerd for the rounding

这不是真的。

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

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

例如,

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

四舍五入到两位小数时。

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

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

这是因为四舍五入后向最高有效位进行四舍五入(第一种情况下为 6,第二种情况下为 8)。

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

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

关于c# - Math.Round 答案使用多少位数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14703041/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com