Class: Amount::Display

Inherits:
Object
  • Object
show all
Defined in:
lib/amount/display.rb

Overview

Formats amounts for UI output without changing their type.

Instance Method Summary collapse

Constructor Details

#initialize(amount) ⇒ Display

Returns a new instance of Display.

Parameters:



9
10
11
12
# File 'lib/amount/display.rb', line 9

def initialize(amount)
  @amount = amount
  @entry = amount.registry_entry
end

Instance Method Details

#formattedString

Returns:

  • (String)


15
16
17
# File 'lib/amount/display.rb', line 15

def formatted
  format("%.#{@entry.decimals}f", @amount.decimal)
end

#in_unit(unit) ⇒ BigDecimal

Parameters:

  • unit (Symbol)

Returns:

  • (BigDecimal)


50
51
52
53
# File 'lib/amount/display.rb', line 50

def in_unit(unit)
  unit_spec = fetch_display_unit(unit)
  @amount.decimal * Amount.coerce_decimal(unit_spec[:scale])
end

#to_sString

Returns:

  • (String)


44
45
46
# File 'lib/amount/display.rb', line 44

def to_s
  "#{@entry.symbol}|#{@amount.decimal.to_s("F")}"
end

#ui(unit: nil, direction: :floor, decorated: true, trim_zeros: nil) ⇒ String

Examples:

Amount.usdc("1.50").ui                       # => "$1.50"
Amount.usdc("1.50").ui(decorated: false)     # => "1.50"
Amount.gold("1").ui(unit: :gram)             # => "31.10 g"
Amount.gold("1").ui(unit: :gram, decorated: false)  # => "31.10"
Amount.sol("2.5").ui(trim_zeros: true)       # => "2.5 SOL"

Parameters:

  • unit (Symbol, nil) (defaults to: nil)
  • direction (Symbol) (defaults to: :floor)
  • decorated (Boolean) (defaults to: true)

    when ‘false`, omit the display symbol and return just the rounded number. Useful when the caller renders the currency label separately (e.g. in a column header or a chip).

  • trim_zeros (Boolean, nil) (defaults to: nil)

    strip trailing zeros from the formatted number. When ‘nil` (the default), falls back to the display unit’s setting, then the registry entry’s setting. An explicit ‘true` or `false` overrides both.

Returns:

  • (String)


35
36
37
38
39
40
41
# File 'lib/amount/display.rb', line 35

def ui(unit: nil, direction: :floor, decorated: true, trim_zeros: nil)
  if unit
    render_display_unit(unit, direction, decorated:, trim_zeros:)
  else
    render_default(direction, decorated:, trim_zeros:)
  end
end