Forum: Ruby on Rails Absolute Value Percentage Difference Question

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
2cfdef9e499a6fad5d009b8d79c868f3?d=identicon&s=25 Becca Girl (newrubygirl)
on 2008-10-20 22:19

I've got a report where I'm making comparisons between 2 different
values.  It's possible for the percentage difference from one value to
the next to be less than or greater than the original number.

If value 2 is 20% greater than OR 20% less than value 1, I want to
highlight that row in a table that I created.

Any thoughts on how to write the correct if statement that would yield
this result?

So far I have diff = (value1 - value2) / value1

.5 = (10-5)/10 which is a 50% decrease between the 2 values

Since the percentage difference is greate than 20%, how can I test that
50% in an if statement to highlight this difference for review?

Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2008-10-20 22:47
(Received via mailing list)
On Oct 20, 2008, at 4:19 PM, Becca Girl wrote:
> Any thoughts on how to write the correct if statement that would yield

def highlight_difference(value1, value2, close_enough=0.8..1.2)
   return nil if value1.nil? || value2.nil?
   return nil if
   return nil if close_enough.include?(value2.to_f/value1)
irb> highlight_difference(10, 5)
=> true
irb> highlight_difference(10, 8)
=> nil
irb> highlight_difference(10, 12)
=> nil
irb> highlight_difference(10, 15)
=> true


Rob Biedenharn
This topic is locked and can not be replied to.