instance method
number_to_currency
Ruby on Rails 4.0.13
Since v4.0.13Signature
number_to_currency(number, options = {})
Formats a number into a currency string (e.g., $13.65). You can customize the format in the options hash.
Options
-
:locale- Sets the locale to be used for formatting (defaults to current locale). -
: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 for non-negative numbers (defaults to “%u%n”). Fields are%ufor the currency, and%nfor the number. -
:negative_format- Sets the format for negative numbers (defaults to prepending an hyphen to the formatted number given by:format). Accepts the same fields than:format, except%nis here the absolute value of the number.
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.506, locale: :fr) # => 1 234 567 890,51 € number_to_currency('123a456') # => $123a456 number_to_currency(-1234567890.50, negative_format: '(%u%n)') # => ($1,234,567,890.50) number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '') # => £1234567890,50 number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u') # => 1234567890,50 £
Parameters
-
numberreq -
optionsopt = {}
Source
# File activesupport/lib/active_support/number_helper.rb, line 201
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
Defined in activesupport/lib/active_support/number_helper.rb line 201
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveSupport::NumberHelper