Class: ReeNumber::NumberToCurrency

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_number/package/ree_number/functions/number_to_currency.rb

Constant Summary collapse

DEFAULTS =
{
  format: "%u%n",
  negative_format: "-%u%n",
  unit: "$",
  separator: ".",
  delimiter: ",",
  precision: 2,
  significant: false,
  strip_insignificant_zeros: false,
  round_mode: :default
}.freeze

Instance Method Summary collapse

Instance Method Details

#call(number, **opts) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ree_lib/packages/ree_number/package/ree_number/functions/number_to_currency.rb', line 53

def call(number, **opts)
  options = DEFAULTS.dup
  options[:negative_format] = "-#{opts[:format]}" if opts[:format]
  options.merge!(opts)
  number_f = Float(number, exception: false)

  if number_f
    if number_f.negative?
      number_f = number_f.abs
      options[:format] = options[:negative_format] if (number_f * 10**options[:precision]) >= 0.5
    end

    number_s = number_to_delimited(
      number_to_rounded(
        number_f, 
        **slice(options, [:precision, :significant, :strip_insignificant_zeros, :round_mode])
      ),
      **slice(options, [:delimiter, :separator])
    )
  else
    number_s = number.to_s.strip
    options[:format] = options[:negative_format] if number_s.sub!(/^-/, "")
  end

  options[:format].gsub("%n", number_s).gsub("%u", options[:unit])
end