小数和浮点数正在发生非常奇怪的事情,我不明白为什么或在哪里(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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句