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?
You can pass some options to
number_to_currency
(a standard Rails 4 view helper):As posted by Dylan Markow
If someone is using Sequel the migration would look something like:
somehow Sequel ignores :precision and :scale
(Sequel Version: sequel (3.39.0, 3.38.0))
If you are using Postgres (and since we're in 2017 now) you might want to give their
:money
column type a try.Common practice for handling currency is to use decimal type. Here is a simple example from "Agile Web Development with Rails"
This will allow you to handle prices from -999,999.99 to 999,999.99
You may also want to include a validation in your items like
to sanity-check your values.
Use money-rails gem. It nicely handles money and currencies in your model and also has a bunch of helpers to format your prices.
You'll probably want to use a
DECIMAL
type in your database. In your migration, do something like this:In Rails, the
:decimal
type is returned asBigDecimal
, which is great for price calculation.If you insist on using integers, you will have to manually convert to and from
BigDecimal
s everywhere, which will probably just become a pain.As pointed out by mcl, to print the price, use: