This section discusses precision math rounding for the 本节讨论ROUND()
function and for inserts into columns with exact-value types (DECIMAL
and integer).ROUND()
函数和具有精确值类型(DECIMAL
和整型数)的列插入的精度数学舍入。
The ROUND()
function rounds differently depending on whether its argument is exact or approximate:ROUND()
函数的舍入方式不同,具体取决于其参数是精确的还是近似的:
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. ROUND()
使用“向上取整”规则:小数部分为.5或更大的值,如果为正,则向上取整为下一个整数;如果为负,则向下取整为下一个整数。(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. 小数部分小于.5的值如果为正,则向下舍入到下一个整数;如果为负,则向上舍入到下一个整数。(In other words, it is rounded toward zero.)(换句话说,它是向零舍入的。)
For approximate-value numbers, the result depends on the C library. 对于近似值数字,结果取决于C库。On many systems, this means that 在许多系统上,这意味着ROUND()
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.ROUND()
使用“舍入到最接近的偶数”规则:小数部分正好位于两个整数中间的值被舍入到最接近的偶数整数。
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 |
+------------+--------------+
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:DECIMAL
或整型数列,目标是精确的数据类型,因此舍入使用“从零舍入一半”,而不管要插入的值是精确的还是近似的:
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)
The SHOW WARNINGS
statement displays the notes that are generated by truncation due to rounding of the fractional part. SHOW WARNINGS
语句显示由于小数部分的舍入而截断生成的注释。Such truncation is not an error, even in strict SQL mode (see Section 12.25.3, “Expression Handling”).即使在严格的SQL模式下,这种截断也不是错误(请参阅第12.25.3节,“表达式处理”)。