
Ask HN: Store price as integer or decimal? - deliriousferret
For an e-commerce website, how would you store products&#x27; price in DB? decimal? pence integer?
======
troels
In the db, it's ok to store as decimal, since it's internally an integer.
However, unless your language/framework has built-in support for money, you
should use a library to deal with it (Or build one). Specifically, you do NOT
want to treat them as floats, so you will probably end up handling them as
integer cents. Because of this, you might as well do the same in the db for
consistency. Also mind that some db-layers may automatically convert decimal
into floats in your application language. So the safer choice is probably to
just store as integer cents. It seems to be the most common scheme, to my
recall.

While you're at it, keep a currency-symbol/code together with your cents in
the same value-object. Just like time is incomplete without a time zone, money
is incomplete without a currency. You will thank me later.

For inspiration,
[RubyMoney]([https://github.com/RubyMoney/money](https://github.com/RubyMoney/money))
is a very well-designed library dealing with this in the context of Ruby.

------
theprotocol
Decimal, because it's straightforward. I prefer to err on the side of
minimizing computations and manipulations involving price, and simple things
are easier to add complexity to later if the need arises compared to the other
way around.

\+ [https://dev.mysql.com/doc/refman/5.7/en/fixed-point-
types.ht...](https://dev.mysql.com/doc/refman/5.7/en/fixed-point-types.html)

> _The DECIMAL and NUMERIC types store exact numeric data values. These types
> are used when it is important to preserve exact precision, for example with
> monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following
> remarks about DECIMAL apply equally to NUMERIC._

------
savethefuture
Integer, divide by 100 to get actual value.

~~~
devianthead
I'm curious as to what makes you say this? IMO this just adds unnecessary
complexity, every time you display a price you'd have to perform an additional
computation. Same goes for persisting the data if you have an administrative
portal for the site - you'd have to edit as decimal store as integer?

