Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 545
Akanksha Avatar asked Nov 22 '25 05:11

Akanksha


2 Answers

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.

like image 189
Aleksei Matiushkin Avatar answered Nov 24 '25 00:11

Aleksei Matiushkin


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.

like image 30
Adam Millerchip Avatar answered Nov 24 '25 00:11

Adam Millerchip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!