2010-11-04 5 views

답변

6

아마도 Money gem을보고 싶을 것입니다.

작동 방식은 센트로 금액을 나타내고 정수를 사용하는 것입니다. 플로트 정밀도를 다룰 필요가 없도록 데이터를 정수로 저장할 수 있습니다.

0

실제로 소수 부분을 사용하지 않은 경우, 즉 사전 계산 된 적분 값 만 저장 한 경우 통화가 제대로 작동합니다. 부동 소수점은 정수를 저장하고 정수 연산을 정확하게 수행합니다.

물론이 시점에서 정수를 사용할 수도 있습니다.

+0

통화로 작업 할 때 "고정 정밀도"번호 라이브러리가 필요하다는 것을 읽었습니다. – timstepp

+0

http://www.codeguru.com/forum/showthread.php?threadid=503157은 토론의 예입니다. – timstepp

1

시몬이 말한 것.

방금 ​​프로젝트에 돈 젬을 삽입 했으므로 머니 유형으로 저장할 수 있습니다.

class Product 
    include Mongoid::Document 

    field :price, type: Money 
end 

Money.class_eval do 

    # Converts an object of this instance into a database friendly value. 
    def mongoize 
    [cents, currency.to_s] 
    end 

    class << self 

    # Get the object as it was stored in the database, and instantiate 
    # this custom class from it. 
    def demongoize(object) 
     cur = object[1] || Money.default_currency 
     Money.new(object[0], cur) 
    end 

    # Takes any possible object and converts it to how it would be 
    # stored in the database. 
    def mongoize(object) 
     case object 
     when Money 
     object.mongoize 
     else object 
     end 
    end 

    # Converts the object that was supplied to a criteria and converts it 
    # into a database friendly form. 
    def evolve(object) 
     case object 
     when Money then object.mongoize 
     else object 
     end 
    end 
    end 

end