MySQL 中 Decimal, Float, Double 的区别

更新日期: 2019-01-13 阅读次数: 18524 分类: MySQL

最近在写小程序商城,不可避免的遇到价格的存储问题

如果要存交易额的话,通常使用什么类型?

凡是跟钱相关的都需要使用 Decimal。

  • Decimal 是精确存储
  • float, double 是近似存储,并不精确

做个简单的测试。

首先建表

CREATE TABLE `payment` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `count` decimal(10,5) DEFAULT NULL,
  `count2` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

然后插入两条数据

select sum(count), sum(count2) from test.payment;

做数值运算

测试 1000.01 == 1000.01

decimal(10, 5) 的参数说明

The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments are as follows:

M is the maximum number of digits (the precision). It has a range of 1 to 65.

D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M.

举例说明

  • decimal(10, 5) 代表有5位小数,5位整数
  • decimal(10, 2) 代表有2位小数,8位整数 (10-2)

超出限制

  • 插入小数如果超过限制会四舍五入
  • 如果整数位超出限制,会报异常 Error Code: 1264. Out of range value for column 'price' at row 1

如何取舍 decimal 的整数位

如果非大交易类型,实际上普通商品价格在 11 位整数是足够的,即 100 亿。所以,使用 decimal(13, 2)

但是对于大资金流水的平台来说,11位是不够的,例如统计 GDP 最好还是在 65 位以下,选个合适的。

是否有哪门语言不支持 Decimal

TODO

参考

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式