Class: Spree::LocalizedNumber

Inherits:
Object
  • Object
show all
Defined in:
lib/spree/localized_number.rb

Class Method Summary (collapse)

Class Method Details

+ (BigDecimal, anything) parse(number)

Given a string, strips all non-price-like characters from it, taking into account locale settings. Returns the input given anything else.

Parameters:

  • number (String, anything)

    the number to be parsed or anything else

Returns:

  • (BigDecimal, anything)

    the number parsed from the string passed in, or whatever you passed in



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/spree/localized_number.rb', line 10

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