Module: Timeprice::CLI::Formatting

Included in:
Presenters::Compare, Presenters::Exchange, Presenters::Inflation
Defined in:
lib/timeprice/cli/formatting.rb

Overview

Number/currency formatting helpers shared by every CLI emitter. Lives as a mixin (rather than a free-standing module function set) so callers can use the helpers as plain methods inside ‘no_commands` blocks.

Instance Method Summary collapse

Instance Method Details

#fmt_money(amount, currency) ⇒ Object



11
12
13
# File 'lib/timeprice/cli/formatting.rb', line 11

def fmt_money(amount, currency)
  with_commas(format("%.#{Supported.decimals_for(currency)}f", amount))
end

#fmt_rate(rate) ⇒ Object

Two decimals once we’re past the unit threshold; six decimals for sub-unit rates so tiny rates (e.g. 0.000045) still carry signal.



17
18
19
20
# File 'lib/timeprice/cli/formatting.rb', line 17

def fmt_rate(rate)
  decimals = rate.to_f.abs >= 1 ? 2 : 6
  with_commas(format("%.#{decimals}f", rate))
end

#round_money(amount, currency) ⇒ Object



22
23
24
# File 'lib/timeprice/cli/formatting.rb', line 22

def round_money(amount, currency)
  amount.to_f.round(Supported.decimals_for(currency))
end

#with_commas(num_str) ⇒ Object



26
27
28
29
30
31
# File 'lib/timeprice/cli/formatting.rb', line 26

def with_commas(num_str)
  sign = num_str.start_with?("-") ? "-" : ""
  whole, frac = num_str.sub(/\A-/, "").split(".", 2)
  whole = whole.reverse.gsub(/(\d{3})(?=\d)/, '\1,').reverse
  frac ? "#{sign}#{whole}.#{frac}" : "#{sign}#{whole}"
end