Skip to content

Instantly share code, notes, and snippets.

@alvir
Created October 2, 2013 06:42
Show Gist options
  • Save alvir/6789869 to your computer and use it in GitHub Desktop.
Save alvir/6789869 to your computer and use it in GitHub Desktop.
Magic signum
def self.percent_by_prices(previous_price, current_price)
return 0 if previous_price.nil? || previous_price.zero?
res = (((current_price.to_f/previous_price.to_f) - 1) * 100).round
res = self.signum(current_price - previous_price) if res.zero?
res
end
def self.signum(number)
case
when number > 0
1
when number < 0
-1
when number == 0
0
end
end
# Specs on signum functionality
context "go to 1" do
it 'should return 1 percent if 0 < result < 1 ' do
described_class.percent_by_prices(1000, 1001).should == 1
end
it 'should return -1 percent if -1 < result < 0 ' do
described_class.percent_by_prices(1000, 999).should == -1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment