Module: Brcobranca::Currency::Number

Defined in:
lib/brcobranca/currency.rb

Overview

Instance Method Summary collapse

Instance Method Details

#to_currency(options = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/brcobranca/currency.rb', line 25

def to_currency(options = {})
  number = self
  default   = Brcobranca::Currency::DEFAULT
  options   = default.merge(options)
  precision = options[:precision] || default[:precision]
  unit      = options[:unit] || default[:unit]
  position  = options[:position] || default[:position]
  separator = precision.positive? ? options[:separator] || default[:separator] : ''
  delimiter = options[:delimiter] || default[:delimiter]

  begin
    parts = number.with_precision(precision).split('.')
    number = parts[0].to_i.with_delimiter(delimiter) + separator + parts[1].to_s
    position == 'before' ? unit + number : number + unit
  rescue StandardError
    number
  end
end

#with_delimiter(delimiter = ',', separator = '.') ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/brcobranca/currency.rb', line 44

def with_delimiter(delimiter = ',', separator = '.')
  number = self
  begin
    parts = number.to_s.split(separator)
    parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
    parts.join separator
  rescue StandardError
    self
  end
end

#with_precision(precision = 3) ⇒ Object



55
56
57
58
# File 'lib/brcobranca/currency.rb', line 55

def with_precision(precision = 3)
  number = self
  "%01.#{precision}f" % number
end