Flowdock
number_to_currency(number, options = {}) public

Formats a number into a currency string. You can customize the format in the options hash.

  • :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 ","
 number_to_currency(1234567890.50)     => $1,234,567,890.50
 number_to_currency(1234567890.506)    => $1,234,567,890.51
 number_to_currency(1234567890.506, :precision => 3)    => $1,234,567,890.506
 number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "")
    => £1234567890,50
Show source
Register or log in to add new notes.
August 29, 2008
5 thanks

Brazilian Real (R$ 1.200,95)

helper:

def number_to_currency_br(number)
  number_to_currency(number, :unit => "R$ ", :separator => ",", :delimiter => ".")
end
October 20, 2008
3 thanks

number_to_euro

in small cells:

12-->
12def number_to_euro(amount)
  number_to_currency(amount,:unit=>'').gsub(' ',nbsp)
end
January 15, 2010
2 thanks

Use this in controllers

Sometimes you’re gonna need this in controllers. Just put this in the controller:

include ActionView::Helpers::NumberHelper
October 4, 2011
2 thanks

How to change format automatically depending on locale...

… without passing locale option.

In your application_helper.rb (or in other helper) place following code:

def number_to_currency(number, options = {})
  options[:locale] ||= I18n.locale
  super(number, options)
end

Then, in your locale files:

en-GB:
  number:
    currency:
      format:
        format: "%n %u"
        unit: "USD"

And that is it :)

October 24, 2012
0 thanks

If you happen to face some weird rounding issue...

i.e.

helper.number_to_currency(187)
=> "190 kr"

check out your… translations! Especially ‘significant’ key… In my case it was

number:
   currency:
     format:
       significant: 'false'

that broke rounding. It should have been

number:
   currency:
     format:
       significant: ! 'false'

And now it works perfectly

helper.number_to_currency(187)
=> "187 kr"