Class: Float

Inherits:
Object show all
Defined in:
lib/overload/float.rb

Instance Method Summary collapse

Instance Method Details

#as_currency(opts = {}) ⇒ Object

Convert float to currenct ‘@sum.as_currency(pretty: false, strip: true, symbol: ’$‘)`



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/overload/float.rb', line 5

def as_currency opts={}
  opts = { symbol: opts } unless opts.is_a?(Hash)

  out = '%.2f' % self
  out = out.sub('.', ',')
  out = out.sub(/(\d)(\d{3}),/, '\1.\2,')
  out = out.sub(/(\d)(\d{3})\./, '\1.\2.')

  # remove decimal places
  out = out.split(',').first if opts[:strip]

  if opts[:pretty]
    out = out.sub(/^([\d\.]+),(\d{2})$/, '<span class="pretty-price"><b>\1</b><small>,\2</small></span> ')
  end

  if symbol = opts[:symbol]
    symbol = symbol.upcase

    if symbol == '$'
      out = '%s%s' % [symbol, out]
    else
      out += " #{symbol}"
    end
  end

  out
end

#dotted(round_to = 2) ⇒ Object



41
42
43
44
# File 'lib/overload/float.rb', line 41

def dotted round_to=2
  main, sufix = sprintf("%.#{round_to}f", self).to_s.split('.').map(&:to_i)
  [main.dotted, sufix].join(',')
end

#format_with_underscoresObject



33
34
35
36
37
38
39
# File 'lib/overload/float.rb', line 33

def format_with_underscores
  if self > 0
    sprintf('%.2f', self).to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1_').reverse.sub('.00', '')
  else
    nil
  end
end