Module: FriendlyNumbers::NumberToCurrency

Defined in:
lib/friendly_numbers/number_to_currency.rb

Constant Summary collapse

DEFAULTS =
{
  precision: 2,
  unit: "$",
  separator: ","
}

Class Method Summary collapse

Class Method Details

.convert(value, options) ⇒ Object

:nodoc:



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/friendly_numbers/number_to_currency.rb', line 11

def convert(value, options) # :nodoc:
  options = DEFAULTS.merge(options)

  whole, part = value.divmod(1)

  parted = partition(whole, options[:separator])

  options[:unit] +
    parted +
    format("%.#{options[:precision]}f", part)[1..-1] # Strip leading 0
end

.partition(whole, separator) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/friendly_numbers/number_to_currency.rb', line 23

def partition(whole, separator)
  whole.to_s.chars.reverse
    .each_slice(3)
    .map(&:join)
    .join(separator)
    .reverse
end