How to convert float to integer?


I have a specific need to convert floats that have only 0 (as fraction) for example :

6.0 => 6
6.2 => I need it to stay float


One option:

def maybe_to_int(float) do
  truncated = trunc(float)
  if truncated == float, do: truncated, else: float

Basically just convert the float to an integer. If they evaluate as equal then it must have had no decimal part. If they are no longer equal, return the float.


Strangely (give vagaries of floats and equality testing across numeric types), this seems to work!

What 1.0 == 1 actually does is convert 1 to 1.0 and compare the same types, which is why it works.

1 Like