Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple approach to currency formatting in Rails

I spent most part of today trying to figure out how to give my integer fields a currency format and was bombarded with a myriad of different approaches from using Money, Rails-Money gems to using custom helper methods or locales.

You can achieve this by using the number_to_currency method. Say you have the following view:

view.html.erb

<ul>
    <li><%= client.payment %></li>
</ul>

Assuming the column payments is of type integer, this will print out just that, a number with no formatting. Ex: 5523

Now add the number_to_currency method and specify which currency unit you'd like to use (can be any)

<ul>
    <li><%= number_to_currency(client.payment, :unit => "$") %></li>
</ul>

Now we get something like this: 5.523.00$

The number_to_currency method helper has some options by default, one of those is that it inverts (as opposed to common practice) the usage of comma and period. These can be modified by adding the options :separator and :delimiter and give them the values you'd like as is below.

<ul>
    <li><%= number_to_currency(client.payment, :unit => "$", :separator => ".", :delimiter => ",") %></li>
</ul>

These are the available options for the number_to_currency method helper (RubyOnRailsAPI):

: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 %u for the currency, and %n for the number.

:negative_format - Sets the format for negative numbers (defaults to prepending a hyphen to the formatted number given by :format). Accepts the same fields than :format, except %n is here the absolute value of the number.

:raise - If true, raises InvalidNumberError when the argument is invalid.
like image 754
Dotol Avatar asked Oct 17 '22 12:10

Dotol


1 Answers

You can do it a few different ways. Personally I would recommend doing this in a decorator (https://github.com/drapergem/draper) to remove some logic and formatting out of the view.

As mentioned in a prior answer you can use number_to_currency and not use other options to get the correct formatting you are looking for. It can take an integer, float, or string.

number_to_currency 10000
=> "$10,000.00"

Another way is to use money-rails (https://github.com/RubyMoney/money-rails) if you want to deal with a Money object:

money = Money.new(10000)
=> #<Money fractional:10000 currency:USD>

humanized_money_with_symbol money
=> "$10,000.00"
like image 108
jdgray Avatar answered Oct 21 '22 05:10

jdgray