Search code examples
elixirphoenix-framework

How to remove trailing zeros after decimal in Elixir/Phoenix?


I have a list of numbers (float): [1.0, 3.0, 0.25, 0.125]

How do I format these numbers in the Phoenix template so that 1.0 and 3.0 can be shown as 1 and 3 respectively, while 0.25 and 0.125 are shown as it is.

Please note, these numbers are coming from database.

I couldn't find anything with Google search.


Solution

  • One might use Kernel.round/1 and Kernel.==/2 to check if the float value is actually an integer.

    Enum.map([1.0, 3.0, 0.25, 0.125], &if round(&1) == &1, do: round(&1), else: &1)
    #⇒ [1, 3, 0.25, 0.125]
    

    Sidenote: this is a very rare case when it’s mandatory to use == and not strict ===.


    Of course, one might convert everything to strings and replace trailing ~r/\.0+\z/ with an empty string, but I find this too kludgy.