Class: Formatting::FormatNumber

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

Instance Method Summary collapse

Constructor Details

#initialize(input_number, opts) ⇒ FormatNumber

Returns a new instance of FormatNumber.



15
16
17
18
19
20
21
22
23
24
# File 'lib/formatting/number.rb', line 15

def initialize(input_number, opts)
  @input_number = input_number

  @thousands_separator = opts.fetch(:thousands_separator) { default_thousands_separator }
  @decimal_separator   = opts.fetch(:decimal_separator) { default_decimal_separator }
  @round           = opts.fetch(:round, 2)
  @min_decimals    = opts.fetch(:min_decimals, 2)
  @explicit_sign   = opts.fetch(:explicit_sign, false)
  @blank_when_zero = opts.fetch(:blank_when_zero, false)
end

Instance Method Details

#formatObject



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
# File 'lib/formatting/number.rb', line 26

def format
  number = input_number

  has_decimals = number.to_s.include?(".")

  if blank_when_zero
    return "" if number.zero?
  end

  # Avoid negative zero.
  number = 0 if number.zero?

  if round
    number = number.round(round) if has_decimals
  end

  integer, decimals = number.to_s.split(".")

  # Separate groups by thousands separator.
  integer.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{thousands_separator}")

  if explicit_sign
    integer = "+#{integer}" if number > 0
  end

  if min_decimals
    decimals ||= "0"
    decimals = decimals.ljust(min_decimals, "0")
  end

  [integer, decimals].compact.join(decimal_separator)
end