【问题标题】:Why is there no ceil(float) in Java?为什么 Java 中没有 ceil(float)?
【发布时间】:2012-06-17 12:21:11
【问题描述】:

假设我想在Java 中将float 舍入为int
例如,

roundUp(0.2) = 1
roundUp(0.7) = 1
roundUp(1.3) = 2
...

我想打电话给Math.ceilMath.round 这样做,但java.lang.Math 不提供ceil(float)。它仅提供ceil(double)。所以我的float 被提升为doubleceil(double) 返回doubleround(double) 返回long,而我需要将float 向上取整为int(而不是long)。

现在我想知道为什么java.lang.Math 只有ceil(double) 而没有ceil(float)

【问题讨论】:

  • 我有点高兴地注意到,您的示例中的数字是双精度数,而不是浮点数!

标签: java floating-point integer


【解决方案1】:

你可以这样做:

value = (int) Math.ceil(value);

如果您知道value 是一个浮点数,那么您可以将结果转换回floatint

Java 库同时提供ceil(float)ceil(double) 是没有意义的,因为所有浮点参数都可以传递给ceil(double) 方法,结果相同。

【讨论】:

  • @PeterLawrey:谢谢,我已经更新了答案,因为问题确实是关于获得int
  • 我想避免铸件。它看起来并不安全。
  • 在这种情况下,您可能无法将其转回float ;)
  • @Michael 您不能将所有可能的float 值转换为intlong,因此它看起来不安全。 ;) BTW ceil(float) 仍然必须返回 float 所以它不会避免任何转换。
  • 我的意思是如果ceil(float) 已经返回float 我会调用round(float) 来获得int 没有任何转换:例如round(ceil(0.3f))
猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 2012-01-10
  • 2012-02-02
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多