How to calculate % change from X to Y in Ruby

1 Answer

0 votes
def percent_change(x, y)
  ((y - x) / x.abs) * 100.0
end

def describe_change(x, y)
  pct = percent_change(x, y)

  if pct > 0
    "From #{x.round(1)} to #{y.round(1)} is a #{pct.round(2)}% increase (+#{pct.round(2)}%)"
  elsif pct < 0
    "From #{x.round(1)} to #{y.round(1)} is a #{pct.abs.round(2)}% decrease (#{pct.round(2)}%)"
  else
    "From #{x.round(1)} to #{y.round(1)} is no change"
  end
end

puts describe_change(-80.0, 120.0)
puts describe_change(120.0, 30.0)



=begin
run:

From -80.0 to 120.0 is a 250.0% increase (+250.0%)
From 120.0 to 30.0 is a 75.0% decrease (-75.0%)

=end

 



answered 14 minutes ago by avibootz
...