为什么 Java 中没有 ceil(float)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11033581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is there no ceil(float) in Java?
提问by Michael
Suppose I would like to round up float
to int
in Java
.
For instance,
假设我想四舍五入float
到int
in Java
。
例如,
roundUp(0.2) = 1
roundUp(0.7) = 1
roundUp(1.3) = 2
...
I would like to call Math.ceil
and Math.round
to do that but java.lang.Math
does not provide ceil(float)
. It provides only ceil(double)
. So my float
is promoted to double
silently, ceil(double)
returns double
and round(double)
returns long
while I need to round up float
to int
(not long
).
我想打电话Math.ceil
并Math.round
这样做,但java.lang.Math
没有提供ceil(float)
。它仅提供ceil(double)
. 所以 myfloat
被提升为double
静默,ceil(double)
返回double
并round(double)
返回,long
而我需要四舍五入float
到int
(not long
)。
Now I wonder why java.lang.Math
has only ceil(double)
and does not have ceil(float)
.
现在我想知道为什么java.lang.Math
只有ceil(double)
和没有ceil(float)
。
回答by Simeon Visser
You can do:
你可以做:
value = (int) Math.ceil(value);
If you know that value
is a float then you can cast the result back to float
or int
.
如果您知道这value
是一个浮点数,那么您可以将结果转换回float
or int
。
It makes no sense for the Java library to provide both ceil(float)
and ceil(double)
as all float arguments can be passed to the ceil(double)
method with the same result.
Java 库提供这两者是没有意义的ceil(float)
,ceil(double)
因为所有浮点参数都可以传递给ceil(double)
具有相同结果的方法。