我如何比较与ActiveRecord的小数领域一个BigDecimal? [英] How can I compare a BigDecimal with ActiveRecord decimal field?
问题描述
假设这样一个模式:
create_table "bills", :force => true do |t|
t.decimal "cost", :precision => 10, :scale => 5
end
我想编写一个函数,写一个新的法案,DB当且仅当它是独一无二的。下面不工作:
I want to write a function that writes a new bill to the DB iff it is unique. The following does not work:
def load_bill_unless_exists(candidate)
incumbents = Bill.scoped.where(:cost => candidate.cost)
candidate.save unless incumbents.exists?
end
由于现任票据和票据的候选人在他们的BigDecimal重新presentation不同的限制,因此:成本=> candidate.cost
测试失败。也就是说,它的比较
because the incumbent bills and the candidate bills have different limits in their BigDecimal representation, so the :cost => candidate.cost
test fails. That is, it's comparing:
candidate: #<Bill id: nil, cost: #<BigDecimal:105e39850,'0.1670576666 6666666E4',27(27)>>
与
incumbent: #<ServiceBill id: 198449, cost: #<BigDecimal:105e35840,'0.167057667E4',18(18)>>
注意应聘者的BigDecimal的再$ P $比现任更多的数字psents成本。
Notice the candidate's BigDecimal represents the cost with more digits than the incumbent.
所以,问题很简单:什么是正确的方式来执行这种比较?我想到:成本=&GT; BigDecimal.new(candidate.cost.to_s,18)
,但是感觉不对 - 例如,哪里是18号来自
So the question is simple: What's the right way to perform this comparison? I contemplated :cost => BigDecimal.new(candidate.cost.to_s, 18)
, but that doesn't feel right -- for example, where does that number 18 come from?
推荐答案
尝试使用的BigDecimal#圆
:
def load_bill_unless_exists(candidate)
incumbents = Bill.scoped.where(:cost => candidate.cost.round(5))
candidate.save unless incumbents.exists?
end
从文档:
取整到最近的1(默认),返回结果为一个BigDecimal。如果n被指定和正时,结果的小数部分具有不多于许多数字多
Round to the nearest 1 (by default), returning the result as a BigDecimal. If n is specified and positive, the fractional part of the result has no more than that many digits.
既然你已经指定了5 precision您的模式,这就是你应该做四舍五入比较时。
Given that you've specified a precision of 5 in your schema, that's what you should be rounding to when doing comparisons.
这篇关于我如何比较与ActiveRecord的小数领域一个BigDecimal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!