Currency Formatting in Ruby on Rails Views
This article will show you some of the various ways you can format currency in Ruby on Rails views.
Published on:October 16, 2012
Formatting a number as currency is easy thanks to the number_to_currency
helper. This helper will take a valid number and format it as currency. It acceps a number of different options that allow complete customization of the displayed value.
number_to_currency(number, options = {})
Options
- :locale - The locale option allows you to specify the locale you wish to use. Defaults to the current locale.
- :precision - Sets the level of precision. Defaults to 2. Precision is the number of decimal places after the decimal.
- :unit - Sets the denomination of the currency. For example: $ for the United States.
- :separator - Specifies the separator to use between the units. For example the "." separates dollars and cents in the US.
- :delimiter - Specifies the separator to use for the thousands delimiter. For example: 123,456.
- :format - Sets the format for non-negative numbers. The current default is "%u%n". The %u specifies the currency ("$") and the %n specifies the number ("123,456")
- :negative_format - Same as format, but applies to negative numbers.
- :raise - If raise is set to true, an exception will be raised if the number isn't a valid number.
Examples
number_to_currency 123456.50 # => $123,456.50
number_to_currency 123456.506 # => $123,456.51
number_to_currency 123456.506, precision: 3 # => $123,456.506
number_to_currency "123a456" # => $123a456
number_to_currency "123a456", raise: true # => ActionView::Helpers::NumberHelper::InvalidNumberError error
number_to_currency -123456.50, :negative_format => "(%u%n)" # => ($123,456.50)
number_to_currency 123456.50, unit: "£", seperator: ",", delimiter: "" # => £123456.50
number_to_currency 123456.50, unit: "£", separator: ",", delimiter: "", format: "%n %u" # => 123456,50 £
Want to try these examples in the Rails console? Simply prefix number_to_currency
with ActionController::Base.helpers
, example:
ActionController::Base.helpers.number_to_currency 123456.50 # => "$123,456.50"
Thanks for reading!