rails float类型号无法正常工作

时间:2010-12-06 03:32:16

标签: ruby-on-rails

  describe "common methods" do

    it "should get right settlement percent" do
      contract = Contract.new
      contract.settlement_percent = 1.1 / 100.0
      contract.settlement_percent.to_f.should == 0.011 
      contract.settlement_percent.to_s.should == "0.011"
    end

  end

1) Contract common methods should 
 Failure/Error: contract.settlement_percent.to_f.should == 0.011
 expected: 0.011,
      got: 0.011000000000000001 (using ==)

3 个答案:

答案 0 :(得分:2)

您可以使用be_close方法来解决此近似问题。只需传递它的值以及您希望比较的接近程度。

这样的事情对你有用:

contract.settlement_percent.to_f.should be_close(0.011, 0.0001)

A little more on be_close here...

答案 1 :(得分:0)

Base-10浮点值总是近似的,因为它们是以二进制编码的。你不应该期望价值是那么精确。

答案 2 :(得分:0)