Float functions on integers

Hi there,
Why doesn’t Elixir’s Float function like ceil work on integer too ?

Because of is_float/1 guard condition.

1 Like

And from a typing perspective what could you possibly hope to accomplish by invoking the floor and ceiling functions on integers that isn’t already covered by the identity function.

He wouldn’t need to normalize or check incomming numeric data. He could just “call through”.

To be more specific here is my problem with this:

iex(5)> Float.ceil(2*1.5)

iex(6)> Float.ceil(2*2)
** (FunctionClauseError) no function clause matching in Float.ceil/2
    (elixir) lib/float.ex:147: Float.ceil(4, 0)

This kind of problem (with variables instead of numbers) occurs in my app.

Using Float.ceil on Integers does not really make much sense generally, because it’s already a ceiling value. But you could do this:

iex(1)> Float.ceil(2*2*1.0)

Maybe something like this would work

if is_float(number), do: Float.ceil(2 * number), else: 2 * number

or a helper function

defp ceil(float) when is_float(float), do: Float.ceil(float)
defp ceil(int) when is_integer(int), do: int

For note, the reason you do not want to send integers into ceil and such functions is that an integer is ‘arbitrary-sized’ and auto-converting it to a float could lose the number, thus returning a wrong and different number.

There could be another guard to integers and just pass them through, but that would also make those functions slower, and since math on the BEAM (without native-compilation) is slow enough as it is…

1 Like