Class: TwitterCldr::Formatters::NumberFormatter

Inherits:
Formatter
  • Object
show all
Defined in:
lib/twitter_cldr/formatters/numbers/number_formatter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data_reader) ⇒ NumberFormatter

Returns a new instance of NumberFormatter.



12
13
14
# File 'lib/twitter_cldr/formatters/numbers/number_formatter.rb', line 12

def initialize(data_reader)
  @data_reader = data_reader
end

Instance Attribute Details

#data_readerObject (readonly)

Returns the value of attribute data_reader.



10
11
12
# File 'lib/twitter_cldr/formatters/numbers/number_formatter.rb', line 10

def data_reader
  @data_reader
end

Instance Method Details

#format(tokens, number, options = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/twitter_cldr/formatters/numbers/number_formatter.rb', line 16

def format(tokens, number, options = {})
  options[:precision] ||= precision_from(number)
  options[:type] ||= :decimal

  prefix, suffix, integer_format, fraction_format = *partition_tokens(tokens)
  number = truncate_number(number, integer_format.format.length)

  int, fraction = parse_number(number, options)
  result =  integer_format.apply(int, options)
  result << fraction_format.apply(fraction, options) if fraction

  number_system.transliterate(
    "#{prefix.to_s}#{result}#{suffix.to_s}"
  )
end

#truncate_number(number, decimal_digits) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/twitter_cldr/formatters/numbers/number_formatter.rb', line 32

def truncate_number(number, decimal_digits)
  if abbreviate?(number)
    factor = [0, number.to_i.abs.to_s.length - decimal_digits].max
    number / (10.0 ** factor)
  else
    number
  end
end