Class: Plurimath::Formatter::NumberFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/plurimath/formatter/number_formatter.rb

Constant Summary collapse

STRING_SYMBOLS =
{
  dot: ".".freeze,
  f: "F".freeze,
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(number, data_reader = {}) ⇒ NumberFormatter

Returns a new instance of NumberFormatter.



13
14
15
16
17
# File 'lib/plurimath/formatter/number_formatter.rb', line 13

def initialize(number, data_reader = {})
  @number = number
  @data_reader = data_reader
  @prefix = "-" if number.negative?
end

Instance Attribute Details

#data_readerObject (readonly)

Returns the value of attribute data_reader.



6
7
8
# File 'lib/plurimath/formatter/number_formatter.rb', line 6

def data_reader
  @data_reader
end

#numberObject (readonly)

Returns the value of attribute number.



6
7
8
# File 'lib/plurimath/formatter/number_formatter.rb', line 6

def number
  @number
end

#prefixObject (readonly)

Returns the value of attribute prefix.



6
7
8
# File 'lib/plurimath/formatter/number_formatter.rb', line 6

def prefix
  @prefix
end

Instance Method Details

#format(precision: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/plurimath/formatter/number_formatter.rb', line 19

def format(precision: nil)
  data_reader[:precision] = precision || precision_from(number)
  int, frac, integer_format, fraction_format, signif_format = *partition_tokens(number)
  result = integer_format.apply(int, data_reader)
  result << fraction_format.apply(frac, data_reader, int) if frac
  result = signif_format.apply(result, integer_format, fraction_format)
  result = "+#{result}" if number.positive? && data_reader[:number_sign] == :plus
  "#{prefix}#{result}"
end