Alessio.Bussolari
Alessio.Bussolari

Reputation: 63

Comma and Dot concurrently on rails in numeric fields

somebody know a trick for use Comma and Dot concurrently in a decimal field, because the international separator is the Dot but in some country is the Comma. i've try with a Before_validation, but i've a lot of problem, sometimes works sometimes doesn't, this is the code:

def update_fields
    [:field_1, :field_2, :field_3].each { |k|
      unless k != nil
        self[k.to_sym] = self.attributes_before_type_cast[k.to_s].gsub(/[.,]/, '.' => '', ',' => '.')
      end
    }
end

thanks in advice.

Upvotes: 0

Views: 237

Answers (2)

territorial
territorial

Reputation: 142

please try it: add it to you GemFile

gem 'i18n_alchemy'

And after :

class MyClass < ActiveRecord::Base
  include I18n::Alchemy
  localize [:field1, field2, field3], using: :number
end

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 120990

Unless you accept thousand separator in your front end, simply change everything to dots:

value.tr!(',', '.')

With thousand separators the task becomes much more convoluted, and the easiest way to handle it is to standardize everything on client side, aka front end, with javascript, since there in browser the user’s locale settings are available.

Upvotes: 0

Related Questions