TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: Store price as integer or decimal?

2 点作者 deliriousferret将近 8 年前
For an e-commerce website, how would you store products' price in DB? decimal? pence integer?

3 条评论

troels将近 8 年前
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.
theprotocol将近 8 年前
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>
savethefuture将近 8 年前
Integer, divide by 100 to get actual value.
评论 #14617094 未加载