Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best method of handling currency/money?

I'm working on a very basic shopping cart system.

I have a table items that has a column price of type integer.

I'm having trouble displaying the price value in my views for prices that include both Euros and cents. Am I missing something obvious as far as handling currency in the Rails framework is concerned?

like image 963
Barry Gallagher Avatar asked Jun 19 '09 20:06

Barry Gallagher


People also ask

What is the best way to exchange large amounts of currency?

Quick Summary. You can use a bank or currency broker to exchange large amounts of currency. The cost is a combination of exchange rates and transfer fees. Currency brokers can normally beat the banks in terms of cost.

What is the best form of currency?

The Swiss franc (CHF) is generally considered to be the safest currency in the world and many investors consider it to be a safe-haven asset. This is due to the neutrality of the Swiss nation, along with its strong monetary policies and low debt levels.

Is it better to exchange money at a bank or currency exchange?

Foreign currency exchange at banks It can be delivered to your local branch for pick up. Exchange rates at banks are slightly better than exchange rates elsewhere. You can also order currency before you leave on your trip from a number of websites that will ship it to your home within a couple of days.


1 Answers

You'll probably want to use a DECIMAL type in your database. In your migration, do something like this:

# precision is the total number of digits # scale is the number of digits to the right of the decimal point add_column :items, :price, :decimal, :precision => 8, :scale => 2 

In Rails, the :decimal type is returned as BigDecimal, which is great for price calculation.

If you insist on using integers, you will have to manually convert to and from BigDecimals everywhere, which will probably just become a pain.

As pointed out by mcl, to print the price, use:

number_to_currency(price, :unit => "€") #=> €1,234.01 
like image 152
molf Avatar answered Oct 09 '22 09:10

molf