views:

44

answers:

2

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

+1  A: 
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
Matthew Vines
+2  A: 

Use integers for storing currency, for example, use store 100 cents for 1 dollar. It reduces headaches and may improve performance if it matters.

Jaryl