开发者

rails float type number does not work right

开发者 https://www.devze.com 2023-01-28 07:28 出处:网络
describe \"common methods\" do it \"should get right settlement percent\" do contract = Contract.new contract.settlement_percent = 1.1 / 100.0
  describe "common methods" do

    it "should get right settlement percent" do
      contract = Contract.new
      contract.settlement_percent = 1.1 / 100.0
      contrac开发者_运维百科t.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 ==)


You can use the be_close method to account for this approximation issue. Just pass it the value and how close you want the comparison to be.

Something like this should work for you:

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

A little more on be_close here...


Base-10 floating point values are always approximated since they're encoded in binary. You shouldn't expect values to be that precise.


Take a look at this post: What is the most effective way for float and double comparison?

0

精彩评论

暂无评论...
验证码 换一张
取 消