Sha256: 3f80d392bc5d0b966af59aac09ef476101e30fa4f045699bf4745fbcd2a4e71b

Contents?: true

Size: 1.01 KB

Versions: 9

Compression:

Stored size: 1.01 KB

Contents

module Spree
  class LocalizedNumber
    # Given a string, strips all non-price-like characters from it,
    # taking into account locale settings. Returns the input given anything
    # else.
    #
    # @param number [String, anything] the number to be parsed or anything else
    # @return [BigDecimal, anything] the number parsed from the string passed
    #   in, or whatever you passed in
    def self.parse(number)
      return number unless number.is_a?(String)

      # I18n.t('number.currency.format.delimiter') could be useful here, but is
      # unnecessary as it is stripped by the non_number_characters gsub.
      separator = I18n.t(:'number.currency.format.separator')
      non_number_characters = /[^0-9\-#{separator}]/

      # strip everything else first
      number = number.gsub(non_number_characters, '')

      # then replace the locale-specific decimal separator with the standard separator if necessary
      number = number.gsub(separator, '.') unless separator == '.'

      number.to_d
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
solidus_core-2.2.2 lib/spree/localized_number.rb
solidus_core-2.1.1 lib/spree/localized_number.rb
solidus_core-2.2.1 lib/spree/localized_number.rb
solidus_core-2.2.0 lib/spree/localized_number.rb
solidus_core-2.2.0.rc1 lib/spree/localized_number.rb
solidus_core-2.2.0.beta1 lib/spree/localized_number.rb
solidus_core-2.1.0 lib/spree/localized_number.rb
solidus_core-2.1.0.rc1 lib/spree/localized_number.rb
solidus_core-2.1.0.beta1 lib/spree/localized_number.rb