Decimals and commas when entering a number into a Ruby on Rails form -


what's best ruby/rails way allow users use decimals or commas when entering number form? in other words, user able enter 2,000.99 , not 2.00 in database.

is there best practice this?

-- update ---

does gsub work floats or bigintegers? or rails automatically cut number off @ , when entering floats or ints form? tried using self.price.gsub(",", "") "undefined method `gsub' 8:fixnum" 8 whatever number entered in form.

i had similar problem trying use localized content inside forms. localizing output relatively simple using actionview::helpers::numberhelper built-in methods, parsing localized input not supported activerecord.

this solution, please, tell me if i'm doing wrong. seems me simple right solution. thanks! :)

first of all, let's add method string.

class string   def to_delocalized_decimal     delimiter = i18n::t('number.format.delimiter')     separator = i18n::t('number.format.separator')     self.gsub(/[#{delimiter}#{separator}]/, delimiter => '', separator => '.')   end end 

then let's add class method activerecord::base

class activerecord::base   def self.attr_localized(*fields)     fields.each |field|       define_method("#{field}=") |value|         self[field] = value.is_a?(string) ? value.to_delocalized_decimal : value       end     end   end end 

finally, let's declare fields should have input localized.

class article < activerecord::base   attr_localized :price end 

now, in form can enter "1.936,27" , activerecord not raise errors on invalid number, because becomes 1936.27.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -