Rails: 在数据库中存储 BigDecimal

Rails: Storing BigDecimal in Database

我正在处理一堆 BigDecimals,我想将它们存储到我的数据库中。理想情况下没有任何精度损失。我不知道实现该目标的最佳方法。


我想到了这个:

t.decimal :value, precision: 1000, scale: 30

这看起来不是解决此问题的好方法。 1.它仍然会影响准确性。 2. 越来越大了。


有没有办法存储对象,例如:#<BigDecimal:586a238,'0.563E0',9(36)> 到数据库(在 text 列中),然后将其重新初始化为 BigDecimal?

您可能想查看 composed_of

但我更喜欢使用自定义 getter 和 setter 方法,因为我认为它们更易于阅读和理解。

示例:假设您的属性名为 foo,并且您想在应用程序中使用 BigDecimal,但将值作为字符串存储在数据库中:

def foo
  BigDecimal.new(read_attribute(:foo))
end

def foo=(foo)
  write_attribute(:foo, foo.to_s)
end

默认情况下,PostgreSQL Decimal 的范围是 "up to 131072 digits before the decimal point; up to 16383 digits after the decimal point"。还不够吗?

https://www.postgresql.org/docs/9.1/static/datatype-numeric.html

只需使用:

t.decimal :value