Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no ceil(float) in Java?

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).

like image 990
Michael Avatar asked Jun 14 '12 12:06

Michael


People also ask

Is there a ceiling function in Java?

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.

What is Math ceil 3.6 in Java?

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.

Why float is not used in Java?

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.


1 Answers

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.

like image 68
Simeon Visser Avatar answered Oct 05 '22 23:10

Simeon Visser