Skip to content

Commit 604a588

Browse files
lifoDavid Heinemeier Hansson
authored andcommitted
Ensure AR#sum result is typecasted properly
1 parent 2af6489 commit 604a588

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

activerecord/lib/active_record/calculations.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,9 @@ def column_for(field)
265265
def type_cast_calculated_value(value, column, operation = nil)
266266
operation = operation.to_s.downcase
267267
case operation
268-
when 'count', 'sum' then value.to_i
269-
when 'avg' then value && value.to_f
268+
when 'count' then value.to_i
269+
when 'sum' then value =~ /\./ ? value.to_f : value.to_i
270+
when 'avg' then value && value.to_f
270271
else column ? column.type_cast(value) : value
271272
end
272273
end

activerecord/test/cases/calculations_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@ def test_should_return_zero_if_sum_conditions_return_nothing
102102
assert_equal 0, companies(:rails_core).companies.sum(:id, :conditions => '1 = 2')
103103
end
104104

105+
def test_sum_should_return_valid_values_for_decimals
106+
NumericData.create(:bank_balance => 19.83)
107+
assert_equal 19.83, NumericData.sum(:bank_balance)
108+
end
109+
105110
def test_should_group_by_summed_field_with_conditions
106111
c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
107112
:group => :firm_id)

0 commit comments

Comments
 (0)