in rails app, want users able input percentage values decimals 0.0 100.0. in database, want store them decimals 0.00 1.00, calculations easier.
i'm doing through getters , setters in model. then, when write derived attributes in model, end using 0-100 values instead of 0-1, defeats purpose of storing in 0-1 values easy calculation:
# in model `quote.rb` def discount=(value) write_attribute :discount, value.to_f / 100 end def discount read_attribute(:discount).to_f * 100 end def final_price price * (1 - discount) # generates wrong value, # because if user inputs discount 50 represent 50%, # final price `price * -49` end
any ideas on better ways achieve this?
i use decimal column (to avoid issues floats , rounding) store raw values (as percentage) , avoid casting.
you can calculate net price using:
def final_price price * (discount || 100 * 0.01) end
when comes dealing presenting output user way want @ money gem makes easier deal locales , multiple currencies.
Comments
Post a Comment