本节讨论用于 ROUND() 函数以及插入到具有精确值类型的列(DECIMAL 和整数)的精度数学四舍五入。This section discusses precision math rounding for the
ROUND() function and for inserts
into columns with exact-value types
(DECIMAL and integer).
ROUND() 函数的四舍五入方式取决于其参数是精确值还是近似值:The ROUND() function rounds
differently depending on whether its argument is exact or
approximate:
对于精确数值,
ROUND()使用“四舍五入” 规则:如果数值的小数部分为 0.5 或更大,则正数向上舍入到下一个整数,负数向下舍入到下一个整数。(换句话说,它是远离零舍入的。)如果数值的小数部分小于 0.5,则正数向下舍入到下一个整数,负数向上舍入到下一个整数。(换句话说,它是向零舍入的。)For exact-value numbers,ROUND()uses the “round half up” 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. (In other words, it is rounded toward zero.)对于近似值数字,结果取决于 C 库。在许多系统上,这意味着
ROUND()使用“四舍五入到最接近的偶数” 规则:一个小数部分正好在两个整数中间的值将被四舍五入到最接近的偶数整数。For approximate-value numbers, the result depends on the C library. On many systems, this means thatROUND()uses the “round to nearest even” rule: A value with a fractional part exactly half way between two integers is rounded to the nearest even integer.
以下示例显示了精确值和近似值的舍入方式有何不同:The following example shows how rounding differs for exact and approximate values:
mysql> SELECT ROUND(2.5), ROUND(25E-1);
+------------+--------------+
| ROUND(2.5) | ROUND(25E-1) |
+------------+--------------+
| 3 | 2 |
+------------+--------------+
对于插入到 DECIMAL 或整数列中,目标是精确的数据类型,因此无论要插入的值是精确还是近似,四舍五入都使用“远离零的四舍五入”:For inserts into a DECIMAL or
integer column, the target is an exact data type, so rounding uses
“round half away from zero,” regardless of whether
the value to be inserted is exact or approximate:
mysql>CREATE TABLE t (d DECIMAL(10,0));Query OK, 0 rows affected (0.00 sec) mysql>INSERT INTO t VALUES(2.5),(2.5E0);Query OK, 2 rows affected, 2 warnings (0.00 sec) Records: 2 Duplicates: 0 Warnings: 2 mysql>SHOW WARNINGS;+-------+------+----------------------------------------+ | Level | Code | Message | +-------+------+----------------------------------------+ | Note | 1265 | Data truncated for column 'd' at row 1 | | Note | 1265 | Data truncated for column 'd' at row 2 | +-------+------+----------------------------------------+ 2 rows in set (0.00 sec) mysql>SELECT d FROM t;+------+ | d | +------+ | 3 | | 3 | +------+ 2 rows in set (0.00 sec)
SHOW WARNINGS 语句显示由于对小数部分进行四舍五入而产生的截断备注。这种截断不是错误,即使在严格 SQL 模式下也是如此(参见 第 14.24.3 节,“表达式处理”)。The SHOW WARNINGS statement
displays the notes that are generated by truncation due to
rounding of the fractional part. Such truncation is not an error,
even in strict SQL mode (see
Section 14.24.3, “Expression Handling”).