Use to_money to convert a string to an integer

Just a quick note: You can use the following code in your helpers/application_helper.rb to convert a string to an integer in your Rails application:

class String
  def to_money
    fee = self.match(/(\d+)(,|.?)(\d{0,2})/)
    if %w(, .).include?(fee[2]) # 56,99 1.00 5,-
      return "#{fee[1]}#{fee[3].to_i.to_s.ljust(2, '0')}"
    elsif fee[1] && fee[2].blank? # 5
      return "#{fee[1]}00"
    end
  end

  def to_money!
    self.replace to_money
  end
end

Now you can do some fancy stuff like the following:

"12 Euro".to_money => 1200
"12 Dollar".to_money => 1200
"12.00 Dollar".to_money => 1200
"12,00 Euro".to_money => 1200
"12,- Euro".to_money => 1200
"1200 Euro".to_money => 120000
money = "12,8 Euro"
money.to_money!
puts money # => 1280

You can read about the motivation why to use integer in favor of decimals in the database here: 7 Top Tips for Coding With Currency.

Tags: ,

Leave a Reply