MySQL 中的精确小数除法

Exact decimal division in MySQL

如何正确划分MySQL中的两个DECIMAL值并得到精确到列类型中定义的位数的结果?

示例:

select cast(1/2 as decimal(4,4)),
cast(1 as decimal(4,4))/2,
cast(1 as decimal(4,4))/cast(2 as decimal(4,4));

结果:

'0.5000', '0.49995000', '1.00000000'

为什么第二个结果不准确?为什么第三个结果不是'0.5000'?

注意:我不能只使用第一种形式,我需要对存储为小数的列进行计算。

问题是 DECIMAL 数据类型声明需要 2 个参数,第一个是总位数,包括小数部分。

根据文档 (http://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html):

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

M is the maximum number of digits (the precision). It has a range of 1 to 65. (Older versions of MySQL permitted a range of 1 to 254.)

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.

因此,如果您使用 5 位而不是 4 位,一切正常:

select cast(1/2 as decimal(5,4)),
cast(1 as decimal(5,4))/2,
cast(1 as decimal(5,4))/cast(2 as decimal(5,4)),
cast(cast(1 as decimal(5,4))/cast(2 as decimal(5,4)) as decimal(5,4));

结果

0.5000, 0.50000000, 0.50000000, 0.5000