The personal finance app for everyone (by everyone)
Ruby
fix(trend): keep percent sign consistent with direction for negative/zero base (#2580)
glorydavid03023d606013e76a1
diff --git a/app/models/trend.rb b/app/models/trend.rbindex 33e2014d74..b5bfe05129 100644--- a/app/models/trend.rb+++ b/app/models/trend.rb@@ -52,11 +52,14 @@ class Trenddef percentreturn 0.0 if previous.zero? && current.zero?- return Float::INFINITY if previous.zero?+ return current.negative? ? -Float::INFINITY : Float::INFINITY if previous.zero?change = (current - previous).to_f- (change / previous.to_f * 100).round(1)+ # Divide by the magnitude of the base so the sign of the percentage always+ # tracks the actual change (and agrees with #direction). Dividing by a signed+ # negative base would otherwise invert the sign (e.g. net worth -100 -> -50).+ (change / previous.to_f.abs * 100).round(1)enddef percent_formatteddiff --git a/test/models/trend_test.rb b/test/models/trend_test.rbindex 64601af195..5dccb42e32 100644--- a/test/models/trend_test.rb+++ b/test/models/trend_test.rb@@ -31,10 +31,28 @@ class TrendTest < ActiveSupport::TestCasetest "infinitely up" dotrend = Trend.new(current: 100, previous: 0)assert_equal "up", trend.direction+ assert_equal Float::INFINITY, trend.percentendtest "infinitely down" dotrend = Trend.new(current: 0, previous: 100)assert_equal "down", trend.directionend++ test "percent sign tracks direction when the base is negative" do+ # Net worth improving from -100 to -50 is a +50% change, not -50%.+ improving = Trend.new(current: -50, previous: -100)+ assert_equal "up", improving.direction+ assert_equal 50.0, improving.percent++ # Net worth worsening from -100 to -150 is a -50% change.+ worsening = Trend.new(current: -150, previous: -100)+ assert_equal "down", worsening.direction+ assert_equal(-50.0, worsening.percent)+ end++ test "percent carries the sign of current when the base is zero" do+ assert_equal(-Float::INFINITY, Trend.new(current: -100, previous: 0).percent)+ assert_equal Float::INFINITY, Trend.new(current: 100, previous: 0).percent+ endend