module ActiveSupport::NumberHelper
def number_to_currency(number, options = {})
number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u')
# => £1234567890,50
number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '')
# => ($1,234,567,890.50)
number_to_currency(-1234567890.50, negative_format: '(%u%n)')
number_to_currency('123a456') # => $123a456
number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
number_to_currency(1234567890.506) # => $1,234,567,890.51
number_to_currency(1234567890.50) # => $1,234,567,890.50
==== Examples
absolute value of the number.
than :format, except %n is here the
number given by :format). Accepts the same fields
numbers (defaults to prepending an hyphen to the formatted
* :negative_format - Sets the format for negative
currency, and %n for the number.
(defaults to "%u%n"). Fields are %u for the
* :format - Sets the format for non-negative numbers
to ",").
* :delimiter - Sets the thousands delimiter (defaults
(defaults to ".").
* :separator - Sets the separator between the units
(defaults to "$").
* :unit - Sets the denomination of the currency
to 2).
* :precision - Sets the level of precision (defaults
(defaults to current locale).
* :locale - Sets the locale to be used for formatting
==== Options
can customize the format in the +options+ hash.
Formats a +number+ into a currency string (e.g., $13.65). You
def number_to_currency(number, options = {}) return unless number options = options.symbolize_keys currency = i18n_format_options(options[:locale], :currency) currency[:negative_format] ||= "-" + currency[:format] if currency[:format] defaults = default_format_options(:currency).merge!(currency) defaults[:negative_format] = "-" + options[:format] if options[:format] options = defaults.merge!(options) unit = options.delete(:unit) format = options.delete(:format) if number.to_f.phase != 0 format = options.delete(:negative_format) number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '') end format.gsub('%n', self.number_to_rounded(number, options)).gsub('%u', unit) end