Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/money/core_extensions.rb

Instance Method Summary collapse

Instance Method Details

#to_money(precision = nil) ⇒ Object

Convert the String to a Money object.

'100'.to_money    #=> #<Money @cents=10000>
'100.37'.to_money #=> #<Money @cents=10037>
'.37'.to_money    #=> #<Money @cents=37>

It takes an optional precision argument which defaults to 2 or the number of digits after the decimal point if it’s more than 2.

'3.479'.to_money  # => #<Money @cents=3479 @precision=3>

Locale support:

 If
  number.format.separator = ","
  number.format.separator = "."
Then
  '100,37'.to_money #=> #<Money @cents=10037>


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/money/core_extensions.rb', line 43

def to_money(precision = nil)
  # Get the currency
  matches = scan /([A-Z]{2,3})/ 
  currency = matches[0] ? matches[0][0] : Money.default_currency

  separator = I18n.translate("number.format.separator", :default => ".")
  delimiter = I18n.translate("number.format.delimiter", :default => ",")

  if !precision
    matches = scan(Regexp.new("\\#{separator}(\\d+)"))
    precision =  matches[0] ? matches[0][0].length : 2
    precision = 2 if precision < 2
  end
  
  # Get the cents amount
  str = self =~ /^(\.|,)/ ? "0#{self}" : self
  matches = str.scan(Regexp.new("(\\-?[\\d\\#{delimiter}]+(\\#{separator}(\\d+))?)"))
  cents = matches[0] ? (matches[0][0].gsub(delimiter, '').gsub(',','.').to_f * 10**precision) : 0

  Money.new(cents, currency, precision)
end