为什么 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:31:42  来源:igfitidea点击:

Why is there no ceil(float) in Java?

javafloating-pointinteger

提问by Michael

Suppose I would like to round up floatto intin Java.
For instance,

假设我想四舍五入floatintin Java
例如,

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

I would like to call Math.ceiland Math.roundto do that but java.lang.Mathdoes not provide ceil(float). It provides only ceil(double). So my floatis promoted to doublesilently, ceil(double)returns doubleand round(double)returns longwhile I need to round up floatto int(not long).

我想打电话Math.ceilMath.round这样做,但java.lang.Math没有提供ceil(float)。它仅提供ceil(double). 所以 myfloat被提升为double静默,ceil(double)返回doubleround(double)返回,long而我需要四舍五入floatint(not long)。

Now I wonder why java.lang.Mathhas 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 valueis a float then you can cast the result back to floator int.

如果您知道这value是一个浮点数,那么您可以将结果转换回floator 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)具有相同结果的方法。