奇怪的舍入问题

恩德涅科夫

小数和浮点数正在发生非常奇怪的事情,我不明白为什么或在哪里(ruby / rails / postgresql)。

给定一个带有小数列购买表-总计

p1 = Purchase.where(total: 5.99).first_or_create
p2 = Purchase.where(total: 5.99).first_or_create

[p1.id, p2.id] # => [1, 2]

p3 = Purchase.where(total: 5.99.to_d).first_or_create
p4 = Purchase.where(total: 5.99.to_d).first_or_create

[p3.id, p4.id] # => [1, 1]

无论是小数还是浮点数,Ruby和postgresql都可以准确地表示5.99,这没有问题:

5.99.to_s         # => "5.99"
5.99.to_d.to_s    # => "5.99"
5.99 == 5.99.to_d # => true

SELECT CAST(5.99 AS DECIMAL) AS decimal, CAST(5.99 AS FLOAT) AS float;
  #  decimal | float 
  # ---------+-------
  #     5.99 |  5.99
  # (1 row)

SELECT CAST(5.99 AS DECIMAL) = CAST(5.99 AS FLOAT) AS equal;
  #  equal 
  # -------
  #  t
  # (1 row)

最重要的是,其他一些值不会发生这种情况:

p5 = Purchase.where(total: 5.75).first_or_create
p6 = Purchase.where(total: 5.75).first_or_create
p7 = Purchase.where(total: 5.75.to_d).first_or_create

[p5.id, p6.id, p7.id] # => [3, 3, 3]
恩德涅科夫

事实证明这是对Rails的一种回归。5.0.0.1可以重现吗???并由5.1.0.0消失了????


将其一分为二,发现此提交可以解决此问题。这是相关的问题

解决方法似乎是停止使用pg gem的float编码器。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章