assert_equal 表示 <0.15>预期但为 <0.15>,但前提是该方法以某种方式计算 0.15
因此,对于此模型方法:
def tax_rate
tax_rate = 0.0
tax_rate += STATE_TAX if state_taxable? #STATE_TAX = 0.1
tax_rate += IMPORT_TAX if imported? #IMPORT_TAX = 0.05
tax_rate
end
此测试失败:
@item.update_attributes({:state_taxable => true,
:imported => true,
:price => 32.19})
assert_equal 0.15, @item.tax_rate
我收到此错误:
<0.15> expected but was <0.15>.
但是,此测试将通过:
@item.update_attributes({:state_taxable => true,
:imported => false,
:price => 14.99})
assert_equal 0.1, @item.tax_rate
因此,当tax_rate执行0.0 + 0.1 + 0.05时,我收到错误,但当它执行0.0 + 0.1或0.0 + 0.05时,则不会收到错误。两个 0.15 都是浮点数,所以我不知道是什么原因造成的。我花了很长时间思考这个问题,希望有人能指出罪魁祸首是什么。预先感谢各位。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
浮点数无法精确表示;您需要做的是使用
assert_in_delta
来检查您是否在指定范围内。像
assert_in_delta 0.15, @item.tax_rate, 0.001
之类的东西应该可以做到:它会检查您是否在预期值的 0.001 范围内。Floating-point numbers can't be represented exactly; what you need to do is use
assert_in_delta
to check you're within a specified range.Something like
assert_in_delta 0.15, @item.tax_rate, 0.001
should do it: it'll check you're within 0.001 of the expected value.恕我直言,您应该存储整数(以分为单位)之类的东西。
IMHO, you should store such things as a integer numbers (in cents).
我多次遇到此错误,这是因为它们是不同的类。
尝试
一下,我相信它会说类似“
如果你这样做
,它可能会过去”之类的内容
I have had this error many times and it's been because they were different classes.
Try
And I am sure it will say something like
If you do
It'll probably pass
0.1
以及其他数字,无法准确表示 在浮点运算中。因此,你应该使用类似的东西(我不是 Ruby 人):一般而言,你不应该真正使用浮动货币/货币:有很多非常令人讨厌的微妙问题,会在裂缝之间损失金钱。请参阅此问题。
0.1
, along with other numbers, cannot be represented exactly in floating-point arithmetics. Hence, you should use something like (I'm no Ruby guy):And generally speaking, you shouldn't really be using floats for money/currency: there are a lot of really nasty subtle issues that will lose money between the cracks. See this question.