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.

Share:
12,824
Michael
Author by

Michael

Scala (moslty) programmer

Updated on June 28, 2022

Comments

  • Michael
    Michael almost 2 years

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

  • Simeon Visser
    Simeon Visser almost 12 years
    @PeterLawrey: thanks, I've updated the answer as the question is indeed about obtaining an int.
  • Michael
    Michael almost 12 years
    I would like to avoid castings. It does not look safe.
  • Vishy
    Vishy almost 12 years
    In which case you may not way to turn it back into a float ;)
  • Vishy
    Vishy almost 12 years
    @Michael You cannot turn all possible float values into an int or long so it shouldn't look safe. ;) BTW ceil(float) would still have to return a float so it doesn't avoid any casting.
  • Michael
    Michael almost 12 years
    I mean that if ceil(float) had returned float I would have called round(float) to get int w/o any casting: e.g. round(ceil(0.3f))