Rail precision floating point accuracy for rail model validation

I am trying to check the dollar amount using a regex: ^[0-9]+\.[0-9]{2}$

This works fine, but whenever a user submits a form and the dollar amount ends with 0 (zero), the ruby ​​(or rails?) Interrupts 0. Thus, 500.00 turns into 500.0, which does not allow checking the correctness of the expression.

Is there any way to make ruby ​​/ rails save the user input format regardless of trailing zeros?

+5
source share
3 answers

I assume that your dollar amount is of decimal type. Thus, any value that the user enters into the field is discarded from the string to the appropriate type before being stored in the database. Validation applies to values ​​already converted to numeric types, so regex is not really a valid validation filter in your case.

You have several options to solve this problem:

  • Use validates_numericality_of. Thus, you completely transfer the conversion to Rails and just check if the quantity is in the given range.
  • Use the method validate_eachand enter the verification logic yourself (for example, check if more than two decimal digits matter).
  • Confirm the attribute before it is created :

, . 0, .

, :

validates_format_of :amount_before_type_cast, :with => /^[0-9]+\.[0-9]{2}$/, :message => "must contain dollars and cents, seperated by a period"

, , ( , , 500 500.00), separator ( - ).

+8

, "" , , float.

, , ... - , , number_to_currency?

+2

Usually with money it is better to store it as an integer in cents (500 cents - $ 5). I use Money gem to handle this.

0
source

All Articles