Mysql。函数 ROUND 没有给出正确的值

Mysql. Function ROUND doesn't give right value

我对此有疑问 select:

select @a := 992.7500, ROUND(@a * (1 + 18 / 100), 2) AS Total;

总计为 1171.44,但其值必须为 1171.45。如果再次执行 Workbench 和我 运行 相同的 select,它会得到正确的值。

¿如何获得正确的价值?谢谢

正确的值。它只是根据 spec.

使用 Banker's Rounding

ROUND() uses the following rules depending on the type of the first argument:

For exact-value numbers, ROUND() uses the “round half away from zero” or “round toward nearest” rule: A value with a fractional part of .5 or greater is rounded up to the next integer if positive or down to the next integer if negative. (In other words, it is rounded away from zero.) A value with a fractional part less than .5 is rounded down to the next integer if positive or up to the next integer if negative.

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.

银行家四舍五入或 "round to nearest even" 是不精确数值(如 double)的首选舍入方法,因为它解决了备选方案的向上偏差。

Bankers Rounding is an algorithm for rounding quantities to integers, in which numbers which are equidistant from the two nearest integers are rounded to the nearest even integer. Thus, 0.5 rounds down to 0; 1.5 rounds up to 2.

如果你使用SET语句,你可以用第一个运行获得正确的值。

SET @a = 992.7500;
select ROUND(@a * (1 + 18 / 100), 2) AS Total;

https://dev.mysql.com/doc/refman/5.6/en/user-variables.html

As a general rule, other than in SET statements, you should never assign a value to a user variable and read the value within the same statement.

Another issue with assigning a value to a variable and reading the value within the same non-SET statement is that the default result type of a variable is based on its type at the start of the statement.

@a是使用SET时的精确数值。在 SELECT 语句中分配的 @a 似乎不是精确值而是近似值数字。

MySQL 8.0(当前)仍然支持您编写的语法,但该语法可能会在 MySQL.

的未来版本中删除

Previous releases of MySQL made it possible to assign a value to a user variable in statements other than SET. This functionality is supported in MySQL 8.0 for backward compatibility but is subject to removal in a future release of MySQL.