You are here

Format Currency in Ruby on Rails

I was looking for a way to display currency data coming from the database as a long. I found out that Ruby on Rails has a buil-in Module Helper method called ActionView::Helpers::NumberHelper:number_to_currency which allows one to format a number according to some options:
 

  • :precision - Sets the level of precision (defaults to 2).
  • :unit - Sets the denomination of the currency (defaults to "$").
  • :separator - Sets the separator between the units (defaults to ".").
  • :delimiter - Sets the thousands delimiter (defaults to ",").
  • :format - Sets the format of the output string (defaults to "%u%n").

 
Using this method, we could write something like this:
 
<%=h number_to_currency @transaction.value, :unit => 'R$', :separator => ",", :delimiter => "." %>
 
This would work fine, but in this solution we are breaking the DRY (Don't Repeat Yourself) rule, because I would need to set the same parameters in every place I was displaying currency values.
 
A better solution would be to have a helper method which I could use in every piece of code where I need a currency. So I came up with the solution below, which consists in writing my own helper method in app/helpers/application_helper.rb:
 
module ApplicationHelper
  def real_currency (number)
    number_to_currency(number,:delimiter => ".", :unit => "R$ ",:separator => ",")
  end
end

 
Now, in my templates I should write something like this:
 
<%=h real_currency @transaction.value %>
 
Ain't that easier?