mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Respect scale of the column in the Decimal type
[Rafael Mendonça França + Jean Boussier]
This commit is contained in:
parent
9f28cb9dc7
commit
4727a94c50
3 changed files with 36 additions and 1 deletions
|
@ -14,7 +14,7 @@ module ActiveRecord
|
|||
private
|
||||
|
||||
def cast_value(value)
|
||||
case value
|
||||
casted_value = case value
|
||||
when ::Float
|
||||
convert_float_to_big_decimal(value)
|
||||
when ::Numeric, ::String
|
||||
|
@ -26,6 +26,8 @@ module ActiveRecord
|
|||
cast_value(value.to_s)
|
||||
end
|
||||
end
|
||||
|
||||
scale ? casted_value.round(scale) : casted_value
|
||||
end
|
||||
|
||||
def convert_float_to_big_decimal(value)
|
||||
|
|
|
@ -946,6 +946,34 @@ class BasicsTest < ActiveRecord::TestCase
|
|||
assert_equal BigDecimal("1000234000567.95"), m1.big_bank_balance
|
||||
end
|
||||
|
||||
def test_numeric_fields_with_scale
|
||||
m = NumericData.new(
|
||||
:bank_balance => 1586.43122334,
|
||||
:big_bank_balance => BigDecimal("234000567.952344"),
|
||||
:world_population => 6000000000,
|
||||
:my_house_population => 3
|
||||
)
|
||||
assert m.save
|
||||
|
||||
m1 = NumericData.find(m.id)
|
||||
assert_not_nil m1
|
||||
|
||||
# As with migration_test.rb, we should make world_population >= 2**62
|
||||
# to cover 64-bit platforms and test it is a Bignum, but the main thing
|
||||
# is that it's an Integer.
|
||||
assert_kind_of Integer, m1.world_population
|
||||
assert_equal 6000000000, m1.world_population
|
||||
|
||||
assert_kind_of Fixnum, m1.my_house_population
|
||||
assert_equal 3, m1.my_house_population
|
||||
|
||||
assert_kind_of BigDecimal, m1.bank_balance
|
||||
assert_equal BigDecimal("1586.43"), m1.bank_balance
|
||||
|
||||
assert_kind_of BigDecimal, m1.big_bank_balance
|
||||
assert_equal BigDecimal("234000567.95"), m1.big_bank_balance
|
||||
end
|
||||
|
||||
def test_auto_id
|
||||
auto = AutoId.new
|
||||
auto.save
|
||||
|
|
|
@ -25,6 +25,11 @@ module ActiveRecord
|
|||
assert_equal BigDecimal("0.33"), type.cast(Rational(1, 3))
|
||||
end
|
||||
|
||||
def test_type_cast_decimal_from_rational_with_precision_and_scale
|
||||
type = Decimal.new(precision: 4, scale: 2)
|
||||
assert_equal BigDecimal("0.33"), type.cast(Rational(1, 3))
|
||||
end
|
||||
|
||||
def test_type_cast_decimal_from_rational_without_precision_defaults_to_18_36
|
||||
type = Decimal.new
|
||||
assert_equal BigDecimal("0.333333333333333333E0"), type.cast(Rational(1, 3))
|
||||
|
|
Loading…
Reference in a new issue