Permalink
Browse files

Merge pull request #16333 from joker1007/fix_decimal_cast_from_float_…

…with_large_precision

Fix type casting to Decimal from Float with large precision

Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information...
2 parents 3d70f07 + 1d6a877 commit b2e88043b52a8f83820a0f4e8a65aa42fd40c544 @senny senny committed Aug 4, 2014
@@ -1,3 +1,7 @@
+* Fix type casting to Decimal from Float with large precision.
+
+ *Tomohiro Hashidate*
+
* Deprecate `Reflection#source_macro`
`Reflection#source_macro` is no longer needed in Active Record
@@ -14,12 +14,25 @@ def type_cast_for_schema(value)
private
def cast_value(value)
- if value.is_a?(::Numeric) || value.is_a?(::String)
+ case value
+ when ::Float
+ BigDecimal(value, float_precision)
+ when ::Numeric, ::String
BigDecimal(value, precision.to_i)
- elsif value.respond_to?(:to_d)
- value.to_d
else
- cast_value(value.to_s)
+ if value.respond_to?(:to_d)
+ value.to_d
+ else
+ cast_value(value.to_s)
+ end
+ end
+ end
+
+ def float_precision
+ if precision.to_i > ::Float::DIG + 1
+ ::Float::DIG + 1
+ else
+ precision.to_i
end
end
end
@@ -10,6 +10,11 @@ def test_type_cast_decimal
assert_equal BigDecimal.new("1"), type.type_cast_from_user(:"1")
end
+ def test_type_cast_decimal_from_float_with_large_precision
+ type = Decimal.new(precision: ::Float::DIG + 2)
+ assert_equal BigDecimal.new("123.0"), type.type_cast_from_user(123.0)
+ end
+
def test_type_cast_decimal_from_rational_with_precision
type = Decimal.new(precision: 2)
assert_equal BigDecimal("0.33"), type.type_cast_from_user(Rational(1, 3))

0 comments on commit b2e8804

Please sign in to comment.