Class: Latinum::Formatters::DecimalCurrencyFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/latinum/formatters.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ DecimalCurrencyFormatter

Returns a new instance of DecimalCurrencyFormatter.



46
47
48
49
50
51
52
53
54
# File 'lib/latinum/formatters.rb', line 46

def initialize(options = {})
  @symbol = options[:symbol] || '$'
  @separator = options[:separator] || '.'
  @delimeter = options[:delimter] || ','
  @places = options[:precision] || 2
  @zero = options[:zero] || '0'

  @name = options[:name]
end

Instance Method Details

#format(amount, options = DEFAULT_OPTIONS) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/latinum/formatters.rb', line 56

def format(amount, options = DEFAULT_OPTIONS)
  # Round to the desired number of places. Truncation used to be the default.
  amount = amount.round(@places)
  
  fix, frac = amount.abs.to_s('F').split(/\./, 2)

  # The sign of the number
  sign = amount.sign < 0 ? '-' : ''

  # Decimal places, e.g. the '.00' in '$10.00'
  frac = frac[0...@places].ljust(@places, @zero)

  # Grouping, e.g. the ',' in '$10,000.00'
  remainder = fix.size % 3
  groups = fix[remainder..-1].scan(/.{3}/).to_a
  groups.unshift(fix[0...remainder]) if remainder > 0

  whole = "#{sign}#{@symbol}#{groups.join(@delimeter)}"
  name = (@name && options[:format] == :full) ? " #{@name}" : ''

  if @places > 0
    "#{whole}#{@separator}#{frac}#{name}"
  else
    "#{whole}#{name}"
  end
end

#from_integral(amount) ⇒ Object



87
88
89
# File 'lib/latinum/formatters.rb', line 87

def from_integral(amount)
  (amount.to_d / 10**@places)
end

#to_integral(amount) ⇒ Object



83
84
85
# File 'lib/latinum/formatters.rb', line 83

def to_integral(amount)
  (amount * 10**@places).to_i
end