Why is there no ceil(float) in Java?
12,824
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
.
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.
Comments
-
Michael almost 2 years
Suppose I would like to round up
float
toint
inJava
.
For instance,roundUp(0.2) = 1 roundUp(0.7) = 1 roundUp(1.3) = 2 ...
I would like to call
Math.ceil
andMath.round
to do that butjava.lang.Math
does not provideceil(float)
. It provides onlyceil(double)
. So myfloat
is promoted todouble
silently,ceil(double)
returnsdouble
andround(double)
returnslong
while I need to round upfloat
toint
(notlong
).Now I wonder why
java.lang.Math
has onlyceil(double)
and does not haveceil(float)
. -
Simeon Visser almost 12 years@PeterLawrey: thanks, I've updated the answer as the question is indeed about obtaining an
int
. -
Michael almost 12 yearsI would like to avoid castings. It does not look safe.
-
Vishy almost 12 yearsIn which case you may not way to turn it back into a
float
;) -
Vishy almost 12 years@Michael You cannot turn all possible
float
values into anint
orlong
so it shouldn't look safe. ;) BTWceil(float)
would still have to return afloat
so it doesn't avoid any casting. -
Michael almost 12 yearsI mean that if
ceil(float)
had returnedfloat
I would have calledround(float)
to getint
w/o any casting: e.g.round(ceil(0.3f))