MySQL 中 Decimal, Float, Double 的区别

发布时间: 2017-09-20 18:41:38 作者: 大象笔记

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

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

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

做个简单的测试。

首先建表

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 的整数位

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

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

是否有哪门语言不支持 Decimal

TODO

参考

我是一名山东烟台的开发者,联系作者