Fix format_according_to_decimals to considers thousands separator

pull/495/head
Felipe Renan 6 years ago
parent 4f07176e08
commit d8baa94de8
  1. 12
      apps/explorer_web/lib/explorer_web/views/currency_helpers.ex
  2. 7
      apps/explorer_web/test/explorer_web/views/currency_helpers_test.exs

@ -55,12 +55,22 @@ defmodule ExplorerWeb.CurrencyHelpers do
iex> format_according_to_decimals(Decimal.new(205000), 12)
"0.000000205"
iex> format_according_to_decimals(Decimal.new(205000), 2)
"2,050"
"""
@spec format_according_to_decimals(Decimal.t(), non_neg_integer()) :: String.t()
def format_according_to_decimals(%Decimal{sign: sign, coef: coef, exp: exp}, decimals) do
sign
|> Decimal.new(coef, exp - decimals)
|> Decimal.reduce()
|> Decimal.to_string(:normal)
|> thousands_separator()
end
defp thousands_separator(value) do
if Decimal.to_float(value) > 999 do
Cldr.Number.to_string!(value)
else
Decimal.to_string(value, :normal)
end
end
end

@ -42,5 +42,12 @@ defmodule ExplorerWeb.CurrencyHelpersTest do
assert CurrencyHelpers.format_according_to_decimals(amount, decimals) == "9.324876"
end
test "formats the value considering thousands separators" do
amount = Decimal.new(1_000_450)
decimals = 2
assert CurrencyHelpers.format_according_to_decimals(amount, decimals) == "10,004.5"
end
end
end

Loading…
Cancel
Save