Class: Math::Percentage

Inherits:
Object
  • Object
show all
Extended by:
ActionView::Helpers::NumberHelper
Defined in:
app/services/math/percentage.rb

Class Method Summary collapse

Class Method Details

.difference(from_value, to_value, precision: 2, strip_insignificant_zeros: true, nil_for_nil: true, add_sign: false, absolute: false) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/services/math/percentage.rb', line 6

def self.difference(from_value, to_value, precision: 2, strip_insignificant_zeros: true, nil_for_nil: true, add_sign: false, absolute: false)

  return if nil_for_nil && from_value.nil? && to_value.nil?

  from_value ||= 0.0
  to_value ||= 0.0

  return 0.0 if from_value == to_value || (from_value.zero? && to_value.zero?)

  r = ((from_value - to_value).to_f.abs / [from_value.abs, to_value.abs].max * 100)
  if from_value > to_value
    r = -r
  end
  if absolute
    r = r.abs
  end
  n = number_with_precision(r, precision: precision, strip_insignificant_zeros: strip_insignificant_zeros)
  n = "#{n} %" if add_sign
  n
end