Format the amount of token transfers in the view

pull/417/head
Felipe Renan 6 years ago
parent 30824949ac
commit aec8c5da84
  1. 2
      apps/explorer_web/lib/explorer_web/templates/address_transaction/_transaction.html.eex
  2. 23
      apps/explorer_web/lib/explorer_web/views/address_transaction_view.ex
  3. 37
      apps/explorer_web/test/explorer_web/views/address_transaction_view_test.exs

@ -76,7 +76,7 @@
</div>
<div class="col-sm-3 col-lg-2 d-flex flex-row flex-sm-column align-items-end">
<span class="tile-title">
<%= token_transfer.amount %> <%= token_transfer.token.symbol %>
<%= formatted_token_amount(token_transfer.amount, token_transfer.token.decimals) %> <%= token_transfer.token.symbol %>
</span>
</div>
<% end %>

@ -21,4 +21,27 @@ defmodule ExplorerWeb.AddressTransactionView do
def transaction_from_or_to_current_address?(transaction, address_hash) do
transaction.from_address_hash == address_hash || transaction.to_address_hash == address_hash
end
@doc """
Formats the given amount according to given decimals.
## Examples
iex> ExplorerWeb.AddressTransactionView.formatted_token_amount(Decimal.new(20500000), 5)
"205"
iex> ExplorerWeb.AddressTransactionView.formatted_token_amount(Decimal.new(20500000), 7)
"2.05"
iex> ExplorerWeb.AddressTransactionView.formatted_token_amount(Decimal.new(205000), 12)
"0.000000205"
"""
@spec formatted_token_amount(Decimal.t(), non_neg_integer()) :: String.t()
def formatted_token_amount(%Decimal{sign: sign, coef: coef, exp: exp}, decimals) do
sign
|> Decimal.new(coef, exp - decimals)
|> Decimal.reduce()
|> Decimal.to_string(:normal)
end
end

@ -0,0 +1,37 @@
defmodule ExplorerWeb.AddresstransactionViewTest do
use ExplorerWeb.ConnCase, async: true
alias ExplorerWeb.AddressTransactionView
doctest ExplorerWeb.AddressTransactionView
describe "formatted_token_amount/1" do
test "formats the amount as value considering the given decimals" do
amount = Decimal.new(205_000_000_000_000)
decimals = 12
assert AddressTransactionView.formatted_token_amount(amount, decimals) == "205"
end
test "considers the decimal places according to the given decimals" do
amount = Decimal.new(205_000)
decimals = 12
assert AddressTransactionView.formatted_token_amount(amount, decimals) == "0.000000205"
end
test "does not consider right zeros in decimal places" do
amount = Decimal.new(90_000_000)
decimals = 6
assert AddressTransactionView.formatted_token_amount(amount, decimals) == "90"
end
test "returns the full number when there is no right zeros in decimal places" do
amount = Decimal.new(9_324_876)
decimals = 6
assert AddressTransactionView.formatted_token_amount(amount, decimals) == "9.324876"
end
end
end
Loading…
Cancel
Save