Module: Fortyk

Included in:
Numeric, String
Defined in:
lib/fortyk.rb

Instance Method Summary collapse

Instance Method Details

#shorten_money(options = {}) ⇒ Object



38
39
40
41
# File 'lib/fortyk.rb', line 38

def shorten_money(options = {})
  options[:currency] ||= "$"
  "#{options[:currency]}#{self.shorten_number}"
end

#shorten_numberObject



2
3
4
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
32
33
34
35
36
# File 'lib/fortyk.rb', line 2

def shorten_number
  if self.is_a?(String)
    self.gsub!(/[a-zA-z$,]/,"")
  end
  num = self.to_i
  string = num.to_s
  length = string.length
  
  case length
  when 4..6 
    label = "K"
    upper = 4
    lower = -3
  when 7..9 
    label = "M"
    upper = 7
    lower = -6
  when 10..12 
    label = "B"
    upper = 10
    lower = -9
  else
    label = nil
  end
  
  if label
    first = string[0..length - upper].to_i
    last = string[lower..lower+2].to_i * 0.001
    last = sprintf("%.1f", last).to_f
    num = first + last
    num = num.round if last.zero? || last == 1
  end
  
  "#{num}#{label}"
end