Thursday, August 12, 2010

Rails number format helper functions

1200.2345.round
o/p: 1200

1200.2345.round_with_precision(2)
o/p: 1200.23


Currency format in rails

number_to_currency is the helper method provided by rails action view helpers. The options were
: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 => 'Rs', :separator => ",", :delimiter => "." %>

This would work fine, but here we 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 in my entire site. A better solution would be to have a helper method which I could use in every where in my application. 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 => "Rs ",:separator => ",")
end
end

Now, I can use <%=h real_currency @transaction.value %> every where in my templates.