Class: Plurimath::Formatter::Numbers::Integer

Inherits:
Base
  • Object
show all
Defined in:
lib/plurimath/formatter/numbers/integer.rb

Constant Summary collapse

DEFAULT_SEPARATOR =
","

Constants inherited from Base

Base::DEFAULT_BASE, Base::DIGIT_VALUE, Base::HEX_ALPHANUMERIC

Instance Attribute Summary collapse

Attributes inherited from Base

#base, #symbols

Instance Method Summary collapse

Constructor Details

#initialize(symbols = {}) ⇒ Integer

Returns a new instance of Integer.



11
12
13
14
15
# File 'lib/plurimath/formatter/numbers/integer.rb', line 11

def initialize(symbols = {})
  super
  @groups    = symbols[:group_digits] || 3
  @separator = symbols[:group] || DEFAULT_SEPARATOR
end

Instance Attribute Details

#groupsObject (readonly)

Returns the value of attribute groups.



7
8
9
# File 'lib/plurimath/formatter/numbers/integer.rb', line 7

def groups
  @groups
end

#separatorObject (readonly)

Returns the value of attribute separator.



7
8
9
# File 'lib/plurimath/formatter/numbers/integer.rb', line 7

def separator
  @separator
end

Instance Method Details

#apply(number) ⇒ Object



17
18
19
# File 'lib/plurimath/formatter/numbers/integer.rb', line 17

def apply(number)
  format_groups(number_to_base(number))
end

#chop_group(string, size) ⇒ Object



32
33
34
# File 'lib/plurimath/formatter/numbers/integer.rb', line 32

def chop_group(string, size)
  string.slice([string.size - size, 0].max, size)
end

#format_groups(string) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/plurimath/formatter/numbers/integer.rb', line 21

def format_groups(string)
  tokens = []

  until string.empty?
    tokens << chop_group(string, groups)
    string = string[0...-tokens.last.size]
  end

  tokens.compact.reverse.join(separator)
end

#number_to_base(number) ⇒ Object



36
37
38
39
40
# File 'lib/plurimath/formatter/numbers/integer.rb', line 36

def number_to_base(number)
  return number if base_default?

  number.to_i.to_s(base)
end