0

I want to force the user to type a number with exact 2 digits after decimal point. Currently when the user types 12.349 it will be converted automatically to 12.35. Instead a validation error should be raised like: "please enter a number with 2 digits after decimal point."

class Accounting < ActiveRecord::Base

  validates :share_ksk, :central_office, :limit_value, :fix_disagio,
            presence: true, numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 }
end

my migration file:

class CreateAccountings < ActiveRecord::Migration
  def change
    create_table :accountings do |t|
      t.decimal :share_ksk,         precision: 5, scale: 2, null: false
      t.decimal :central_office,    precision: 5, scale: 2, null: false
      t.decimal :limit_value,       precision: 5, scale: 2, null: false
      t.decimal :fix_disagio,       precision: 5, scale: 2, null: false

      t.timestamps null: false
    end
  end
end
StandardNerd
  • 4,093
  • 9
  • 46
  • 77

1 Answers1

1

You can do this with the format validation, giving it a regular expression:

validates :share_ksk, :central_office, :limit_value, :fix_disagio,
          presence: true, 
          numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 },
          format: { with: /\d*\.\d{2}$/, message: "must have two digits after decimal point" }

See: http://guides.rubyonrails.org/active_record_validations.html#format

Ryenski
  • 9,582
  • 3
  • 43
  • 47
  • See also http://stackoverflow.com/questions/5562657/how-to-validate-the-number-of-decimal-for-a-numeric-value, http://stackoverflow.com/questions/4173530/ruby-on-rails-validate-a-cost – Ryenski Nov 17 '15 at 22:41
  • 2
    Also, use a number field with a "step" value of ".01". That doesn't prevent people from inputting bad data but it will help avoid it. – Michael Chaney Nov 17 '15 at 22:42
  • @mysmallidea & MichaelChaney, that's awesome, thanks for the hint! – StandardNerd Nov 18 '15 at 09:11