Better way to format decimal to 2 decimal place in liveview template

Hi :hand_with_index_finger_and_thumb_crossed:

I am trying to format currency (eg, 5.32) in liveview template, currently I am using Decimal package to format the number in template like so:

<span class="ml-2"><%= Decimal.new(cashflow_entry.amount) |> Decimal.round(2) %></span>

The output is fine. but few questions came out of my mind:

  1. Does it affect change tracking? change tracking still work?

  2. Is there anyway to specify in Phoenix Ecto schema, so the 2 decimal places is the default for display. according to my understanding, changeset is for change, what about display one?
    I am thinking → define once then forget about it :slight_smile:

  3. if the second idea doesn’t exists, i guess it would be better to create a custom function to format the decimal right? like format_decimal(5.32) for use in template.

I am new to phoenix ecto and came from Django, django provide built-in function to format such number, therefore I am trying to accomplish the same. :slight_smile:

I am not sure there is something to track, it looks like part of a list, if the list change, it will change…
I say this because there is no @var to track :slight_smile:

I much prefer a custom helper function than modifying schema.

You could pass the number of decimal as parameter, You never know…

def format_decimal(value, decimals \\ 2) do
  ...
end
1 Like

The issue with custom functions and change tracking is much more the result of the function. Any change to the input will make the function rerun and any markup depending on the result rerender. That’s not a problem if the complete result needs rerendering anyways, but can be quite problematic if that’s not the case.

Though why not use a function component, where you can also configure the number of decimals as attribute? I like this because it also allows me to put things in a tag, put e.g. markers for tests on them and so on.

2 Likes