Reputation: 2556
I have a variable i would like to force to have 2 and always 2 decimals. Im comparing to a currency. Often i get a comparison looking like the following.
if self.price != price
#do something
end
Where self.price = 120.00
and price = 120.0
. The self.price
is set with a :precision => 2
in the model, but how do i do the same with a variable, cause this seems to fail in comparison
Upvotes: 2
Views: 584
Reputation: 2601
Use integers for storing currency, for example, use store 100 cents for 1 dollar. It reduces headaches and may improve performance if it matters.
Upvotes: 3
Reputation: 27581
class Numeric
def round_to( decimals=0 )
factor = 10.0**decimals
(self*factor).round / factor
end
end
if self.price.round_to(2) != price.round_to(2)
#do something
end
Upvotes: 1