Settings

Theme

Ask HN: Store price as integer or decimal?

2 points by deliriousferret 9 years ago · 4 comments · 1 min read


For an e-commerce website, how would you store products' price in DB? decimal? pence integer?

troels 9 years ago

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) is a very well-designed library dealing with this in the context of Ruby.

theprotocol 9 years ago

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...

>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 9 years ago

Integer, divide by 100 to get actual value.

  • devianthead 9 years ago

    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?

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection