Class: Plurimath::Formatter::NumberFormatter
- Inherits:
-
Object
- Object
- Plurimath::Formatter::NumberFormatter
- Defined in:
- lib/plurimath/formatter/number_formatter.rb
Constant Summary collapse
- DEFAULT_BASE =
Numbers::Base::DEFAULT_BASE
- HEX_ALPHABETS =
"abcdef".freeze
- STRING_SYMBOLS =
{ dot: ".", f: "F", }.freeze
- DEFAULT_BASE_PREFIXES =
{ 2 => "0b", 8 => "0o", 10 => "", 16 => "0x", }.freeze
Instance Attribute Summary collapse
-
#data_reader ⇒ Object
readonly
Returns the value of attribute data_reader.
-
#number ⇒ Object
readonly
Returns the value of attribute number.
Instance Method Summary collapse
- #format(precision: nil) ⇒ Object
-
#initialize(number, data_reader = {}) ⇒ NumberFormatter
constructor
A new instance of NumberFormatter.
Constructor Details
#initialize(number, data_reader = {}) ⇒ NumberFormatter
Returns a new instance of NumberFormatter.
21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/plurimath/formatter/number_formatter.rb', line 21 def initialize(number, data_reader = {}) @number = number @data_reader = data_reader @base = data_reader[:base] || DEFAULT_BASE raise UnsupportedBase.new(@base, DEFAULT_BASE_PREFIXES) unless DEFAULT_BASE_PREFIXES.key?(@base) # Handle base_prefix: if explicitly provided (even as nil), use it; otherwise use default @base_prefix = if data_reader.key?(:base_prefix) data_reader[:base_prefix].to_s else DEFAULT_BASE_PREFIXES[@base] end end |
Instance Attribute Details
#data_reader ⇒ Object (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 |
#number ⇒ Object (readonly)
Returns the value of attribute number.
6 7 8 |
# File 'lib/plurimath/formatter/number_formatter.rb', line 6 def number @number end |
Instance Method Details
#format(precision: nil) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/plurimath/formatter/number_formatter.rb', line 35 def format(precision: nil) data_reader[:precision] = precision || precision_from(number) int, frac, integer_format, fraction_format, signif_format = *partition_tokens(number) # FIX FOR: # NotImplementedError: String#<< not supported. Mutable String methods are not supported in Opal. result = [] result << integer_format.apply(int) result << fraction_format.apply(frac, result, integer_format) # use formatted int for correct fraction formatting result = result.join result = signif_format.apply(result, integer_format, fraction_format) result = result.tr(HEX_ALPHABETS, HEX_ALPHABETS.upcase) if upcase_hex? result = pre_post_fixed(result) unless base_default? "#{prefix_symbol}#{result}" end |