Suppose I would like to round up float
to int
in Java
.
For instance,
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
).
Now I wonder why java.lang.Math
has only ceil(double)
and does not have ceil(float)
.
Java Math ceil() The ceil() method rounds the specified double value upward and returns it. The rounded value will be equal to the mathematical integer. That is, the value 3.24 will be rounded to 4.0 which is equal to integer 4.
Description. The java.lang.Math.ceil(double a) returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
Java does not use it as the default floating-point number. It is the default data type for floating-point numbers. There will be no data loss if we convert float to double. There will be data loss if we convert double to float.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With