Mysql 5.5+ 中的舍入误差?

Rounding error in Mysql 5.5+?

我有一个奇怪的舍入问题。

这是设置(MySQL5.5 Percona;在 Mysql 5.7 CE 中相同):

CREATE TABLE `roundingtest` (
`RT_Double` DOUBLE NULL DEFAULT NULL,
`RT_Float` FLOAT NULL DEFAULT NULL,
`RT_Decimal` DECIMAL(10,3) NULL DEFAULT NULL
)
ENGINE=InnoDB;

现在在 3 个字段中分别输入“1.785”。

现在执行这个查询:

SELECT
1.785, ROUND(1.785, 2),
RT_Double, ROUND(RT_Double, 2),
RT_Float, ROUND(RT_Float, 2),
RT_Decimal, ROUND(RT_Decimal, 2)
FROM roundingtest

结果如下:

如果四舍五入到小数点后一位:

有人请解释这个行为...

只有 DECIMAL 字段是正确的,即使只有 3 位小数。

这可能是由于浮点数在计算机上的保存方式,并不完全准确(因为是以 2 为基数而不是以 10 为基数保存的)。如果将 1.785 保存为 1.784998,则会向下舍入。如果保存为1.785001,则向上取整。

来自MySQL Rounding Behaviour

For approximate-value numbers, the result depends on the C library. On many systems, this means that ROUND() uses the “round to nearest even” rule: A value with any fractional part is rounded to the nearest even integer.

这意味着浮点数可能会四舍五入到最接近的偶数。 DECIMAL 数字被认为是精确的,因此 0.5 或更多的小数部分被四舍五入。