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.
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.
You could use Decimal.reduce/1:
Enum.map(
[1.0, 3.0, 0.25, 0.125],
&(&1 |> Decimal.from_float() |> Decimal.reduce() |> Decimal.to_string())
)
Output:
["1", "3", "0.25", "0.125"]
Decimal is not in the standard library, so you will need to add {:decimal, "~> 1.0"} to mix.exs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With