为什么C#Math.Ceiling向下舍入?

时间:2016-04-05 15:40:51

标签: c# math

我有一个艰难的一天,但有些事情没有正确加入。

在我的C#代码中,我有这个:

Math.Ceiling((decimal)(this.TotalRecordCount / this.PageSize))

(int)TotalRecordCount = 12且(int)PageSize = 5。我得到的结果是2.
(两个值都是int值。)

根据我的计算,12/5 = 2.4。我以为Math.Ceiling总会围捕,在这种情况下,给我3?

PS,如果我这样做:

Math.Ceiling(this.TotalRecordCount / this.PageSize)

我收到消息:

  

Math.Ceiling(this.TotalRecordCount / this.PageSize)
  以下方法或属性之间的调用不明确:
  'System.Math.Ceiling(decimal)'和'System.Math.Ceiling(double)'

2 个答案:

答案 0 :(得分:20)

你看到"四舍五入"因为截断发生在到达Math.Ceiling之前。

当你这样做时

(this.TotalRecordCount / this.PageSize)

它是一个整数除法,其结果是截断的int;把它投到decimal已经太晚了。

要解决此问题,请在分割前进行投射:

Math.Ceiling(((decimal)this.TotalRecordCount / this.PageSize))

答案 1 :(得分:7)

因为 TotalRecordCount PageSize 是int,并且int division向下舍入。您必须将至少一个操作数转换为十进制才能使用十进制除法:

Math.Ceiling((decimal)this.TotalRecordCount / this.PageSize));
相关问题