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

前端 未结 8 765
生来不讨喜
生来不讨喜 2020-12-08 16:19

What\'s the best Ruby/Rails way to allow users to use decimals or commas when entering a number into a form? In other words, I would like the user be able to enter 2,000.99

相关标签:
8条回答
  • 2020-12-08 17:09

    I have written following code in my project. This solved all of my problems.

    config/initializers/decimal_with_comma.rb

    # frozen_string_literal: true
    
    module ActiveRecord
      module Type
        class Decimal
          private
    
          alias_method :cast_value_without_comma_separator, :cast_value
    
          def cast_value(value)
            value = value.gsub(',', '') if value.is_a?(::String)
            cast_value_without_comma_separator(value)
          end
        end
    
        class Float
          private
    
          alias_method :cast_value_without_comma_separator, :cast_value
    
          def cast_value(value)
            value = value.gsub(',', '') if value.is_a?(::String)
            cast_value_without_comma_separator(value)
          end
        end
    
        class Integer
          private
    
          alias_method :cast_value_without_comma_separator, :cast_value
    
          def cast_value(value)
            value = value.gsub(',', '') if value.is_a?(::String)
            cast_value_without_comma_separator(value)
          end
        end
      end
    end
    
    module ActiveModel
      module Validations
        class NumericalityValidator
          protected
    
            def parse_raw_value_as_a_number(raw_value)
              raw_value = raw_value.gsub(',', '') if raw_value.is_a?(::String)
              Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
            end
        end
      end
    end
    
    0 讨论(0)
  • 2020-12-08 17:11

    Take a look at the i18n_alchemy gem for date & number parsing and localization.

    I18nAlchemy aims to handle date, time and number parsing, based on current I18n locale format. The main idea is to have ORMs, such as ActiveRecord for now, to automatically accept dates/numbers given in the current locale format, and return these values localized as well.

    0 讨论(0)
提交回复
热议问题