How do I validate currency format if I am storing in cents?

Hi all -

To avoid floating point issues, I’ve decided to store monetary values in
cents in the database. However, the user will enter these in dollars
and cents. Two questions:

  1. How do I do the validation for the currency format? It looks like
    ActiveRecord truncates the cents since it thinks the field type is a
    Fixnum. Am I forced to do validation in the controller?

  2. Where is the appropriate place to do the conversion from dollars to
    cents? I initially was thinking of doing the conversion in
    before_create or before_update, but again, it seems like the value is
    truncated as described above.

Thanks.

Ken

Kenneth L. wrote:

Hi all -

To avoid floating point issues, I’ve decided to store monetary values in
cents in the database. However, the user will enter these in dollars
and cents. Two questions:

  1. How do I do the validation for the currency format? It looks like
    ActiveRecord truncates the cents since it thinks the field type is a
    Fixnum. Am I forced to do validation in the controller?

  2. Where is the appropriate place to do the conversion from dollars to
    cents? I initially was thinking of doing the conversion in
    before_create or before_update, but again, it seems like the value is
    truncated as described above.

Here’s what I do for conversion:

def amount=(new_amount)
write_attribute(“amount”, (new_amount.to_f * 100.0).to_i)
end

def amount
read_attribute(“amount”).to_f / 100.0
end

I’m not quite sure what I’d validate about it, though:-)

–Al Evans

Al, that puts me on the right track for my second question.

As for the validation, I want to validate to make sure the user did not
enter something that doesn’t match /\d+.\d{2}/. Like a string, for
example.

Do you have a validation like the following?

validates_numericality_of :amount, :only_integer => true

If the user enters a string, doesn’t that break your amount accessors?

Ken

Kenneth L. wrote:

If the user enters a string, doesn’t that break your amount accessors?

Nope. They just come out to 0. Try “fred”.to_f

–Al Evans

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs