Class: Scruffy::Formatters::Number
- Defined in:
- lib/scruffy/formatters.rb
Overview
Default number formatter. Limits precision, beautifies numbers.
Instance Attribute Summary collapse
-
#delimiter ⇒ Object
Returns the value of attribute delimiter.
-
#precision ⇒ Object
Returns the value of attribute precision.
-
#precision_limit ⇒ Object
Returns the value of attribute precision_limit.
-
#separator ⇒ Object
Returns the value of attribute separator.
Instance Method Summary collapse
-
#format(target, idx, options) ⇒ Object
Formats the value.
-
#initialize(options = {}) ⇒ Number
constructor
Returns a new Number formatter.
Methods inherited from Base
Constructor Details
#initialize(options = {}) ⇒ Number
Returns a new Number formatter.
Options:
- precision
-
precision to use for value. Can be set to an integer, :none or :auto. :auto will use whatever precision is necessary to portray all the numerical information, up to :precision_limit.
Example: [100.1, 100.44, 200.323] will result in [100.100, 100.440, 200.323]
- separator
-
decimal separator. Defaults to ‘.’
- delimiter
-
delimiter character. Defaults to ‘,’
- precision_limit
-
upper limit for auto precision.
85 86 87 88 89 90 |
# File 'lib/scruffy/formatters.rb', line 85 def initialize( = {}) @precision = [:precision] || :none @separator = [:separator] || '.' @delimiter = [:delimiter] || ',' @precision_limit = [:precision_limit] || 4 end |
Instance Attribute Details
#delimiter ⇒ Object
Returns the value of attribute delimiter.
71 72 73 |
# File 'lib/scruffy/formatters.rb', line 71 def delimiter @delimiter end |
#precision ⇒ Object
Returns the value of attribute precision.
71 72 73 |
# File 'lib/scruffy/formatters.rb', line 71 def precision @precision end |
#precision_limit ⇒ Object
Returns the value of attribute precision_limit.
71 72 73 |
# File 'lib/scruffy/formatters.rb', line 71 def precision_limit @precision_limit end |
#separator ⇒ Object
Returns the value of attribute separator.
71 72 73 |
# File 'lib/scruffy/formatters.rb', line 71 def separator @separator end |
Instance Method Details
#format(target, idx, options) ⇒ Object
Formats the value.
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/scruffy/formatters.rb', line 93 def format(target, idx, ) my_precision = @precision if @precision == :auto my_precision = [:all_values].inject(0) do |highest, current| cur = current.to_f.to_s.split(".").last.size cur > highest ? cur : highest end my_precision = @precision_limit if my_precision > @precision_limit elsif @precision == :none my_precision = 0 end my_separator = @separator my_separator = "" unless my_precision > 0 begin parts = number_with_precision(target, my_precision).split('.') number = parts[0].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + my_separator + parts[1].to_s number rescue StandardError => e target end end |