TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Ask HN: Store price as integer or decimal?

2 pointsby deliriousferretalmost 8 years ago
For an e-commerce website, how would you store products' price in DB? decimal? pence integer?

3 comments

troelsalmost 8 years ago
In the db, it&#x27;s ok to store as decimal, since it&#x27;s internally an integer. However, unless your language&#x2F;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.<p>While you&#x27;re at it, keep a currency-symbol&#x2F;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.<p>For inspiration, [RubyMoney](<a href="https:&#x2F;&#x2F;github.com&#x2F;RubyMoney&#x2F;money" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;RubyMoney&#x2F;money</a>) is a very well-designed library dealing with this in the context of Ruby.
theprotocolalmost 8 years ago
Decimal, because it&#x27;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.<p>+ <a href="https:&#x2F;&#x2F;dev.mysql.com&#x2F;doc&#x2F;refman&#x2F;5.7&#x2F;en&#x2F;fixed-point-types.html" rel="nofollow">https:&#x2F;&#x2F;dev.mysql.com&#x2F;doc&#x2F;refman&#x2F;5.7&#x2F;en&#x2F;fixed-point-types.ht...</a><p>&gt;<i>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.</i>
savethefuturealmost 8 years ago
Integer, divide by 100 to get actual value.
评论 #14617094 未加载