public Method

NumberHelper.number_to_currency(number, options = {})

Contents:

Formats a number into a currency string (e.g., $13.65). You can customize the format in the options hash.

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 ",").

Examples

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

Source Code

# File action_view/helpers/number_helper.rb, line 65
def number_to_currency(number, options = {})
  options   = options.stringify_keys
  precision = options["precision"] || 2
  unit      = options["unit"] || "$"
  separator = precision > 0 ? options["separator"] || "." : ""
  delimiter = options["delimiter"] || ","

  begin
    parts = number_with_precision(number, precision).split('.')
    unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s
  rescue
    number
  end
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.