我可以在Mysql中将价格存储为十进制或整数吗? [英] Sould I store price as decimal or Integer in Mysql?

查看:294
本文介绍了我可以在Mysql中将价格存储为十进制或整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用十进制来存储价格数据(将4.2美元存储为4.20),但似乎有一些难以比较的平等,即需要计算之间的差异2个数字( abs(number1 - number 2)< 0.01 )而不是使用 number1 == number2

I'm currently using decimal to store price data (store $4.2 as 4.20), but it seems having some difficults to comparing equality, i.e. need to calculate the different between 2 numbers(abs(number1 - number 2) < 0.01) rather than using number1 == number2

所以我想知道将价格存储为整数会更好,比如将商店4.2美元定为420。

So I'm wondering if it will be better to store price as integers, say store $4.2 as 420.

谢谢。

推荐答案

您可以使用所谓的次要货币。这基本上是将4.20美元存储为420.这种做法通常在与支付处理网关或API进行通信时进行调整。

You can use what's known as minor currency. Which is basicly storing $4.20 as 420. This is a practice that is commonly adapted when communicating with payment processing gateways or api.

好处是数据库中的所有算术操作和存储使用整数而不是小数。这意味着它们占用的空间更少,操作更快。

The benefit is that all arithmatic operations in the database and storage happens using integers rather than decimals. Which means they take up less space and operations are faster.

正如@thilo所指出的那样,你也可以避免浮点错误,它有时会蔓延。

As pointed out by @thilo you also avoid floating point erros that can sometimes creep in.

在显示时,只需除以100

At the time of display, simply divide by 100

这篇关于我可以在Mysql中将价格存储为十进制或整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆