Class: FantasticCurrency::Currency

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

Class Method Summary collapse

Class Method Details

.format(value, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/fantastic_currency.rb', line 9

def self.format(value, options={})
  options = {
    :currency => nil,
    :format => false,
    :extra_zeros => false,
    :delimiter => ",",
    :separator => ".",
    :free_as_text => true,
    :display_unit => true,
    :before_unit => "",
    :after_unit => " ",
    :convert_to => nil,
    :precise_input => false,
  }.merge(options)
  
  if options[:precise_input] == true
    value = BigDecimal.new(value.to_s) * 10**FantasticCurrency::Config.get_currency(options[:currency])[:precision]
  end
  
  if options[:convert_to]
    source_currency = FantasticCurrency::Config.get_currency(options[:currency])
    dest_currency = FantasticCurrency::Config.get_currency(options[:convert_to])
    value = value * BigDecimal.new(source_currency[:nominal_value].to_s) / BigDecimal.new(dest_currency[:nominal_value].to_s)
    value = value / 10**(source_currency[:precision] - dest_currency[:precision])
    
    active_currency = dest_currency
  else
    active_currency = FantasticCurrency::Config.get_currency(options[:currency])
  end
  
  precision_factor = 10**active_currency[:precision]

  if options[:format] == true
    if value == 0 and options[:free_as_text]
      return "free"
    end
    helper = FantasticCurrency::Helper.instance
    
    if options[:extra_zeros] == false and (value.to_i / precision_factor * precision_factor) == value.to_i
      precision = 0
    else
      precision = active_currency[:precision]
    end
    
    value_as_string = helper.number_with_precision(BigDecimal.new(value.to_s) / precision_factor,
      :precision => precision,
      :delimiter => options[:delimiter],
      :separator => options[:separator])
    
    if options[:display_unit] == true
      options[:before_unit] + active_currency[:symbol] + options[:after_unit] + value_as_string
    else
      value_as_string
    end
  else
    BigDecimal.new(value.to_s) / precision_factor
  end
  
end