DECIMAL 和 NUMERIC 类型存储精确的数值数据。当保持精确度非常重要时(例如处理货币数据)会使用这些类型。在 MySQL 中,NUMERIC 被实现为 DECIMAL,所以关于 DECIMAL 的以下说明同样适用于 NUMERIC。The DECIMAL and NUMERIC
types store exact numeric data values. These types are used when
it is important to preserve exact precision, for example with
monetary data. In MySQL, NUMERIC is
implemented as DECIMAL, so the following
remarks about DECIMAL apply equally to
NUMERIC.
MySQL 将 DECIMAL 值存储为二进制格式。请参见 第 14.24 节,“精度计算”。MySQL stores DECIMAL values in binary format.
See Section 14.24, “Precision Math”.
在 DECIMAL 列声明中,可以(通常也会)指定精度和小数位。例如:In a DECIMAL column declaration, the
precision and scale can be (and usually is) specified. For
example:
salary DECIMAL(5,2)
在这个例子中,5 是精度,2 是小数位。精度表示存储值的有效数字位数,小数位表示小数点后可以存储的数字位数。In this example, 5 is the precision and
2 is the scale. The precision represents the
number of significant digits that are stored for values, and the
scale represents the number of digits that can be stored
following the decimal point.
标准 SQL 要求 DECIMAL(5,2) 能够存储任意五位数字且有两位小数的值,因此 salary 列中可以存储的值范围是 -999.99 到 999.99。Standard SQL requires that DECIMAL(5,2) be
able to store any value with five digits and two decimals, so
values that can be stored in the salary
column range from -999.99 to
999.99.
在标准 SQL 中,语法 DECIMAL( 等同于 M)DECIMAL(。同样,语法 M,0)DECIMAL 等同于 DECIMAL(,其中实现可以决定 M,0)M 的值。MySQL 支持 DECIMAL 语法的这两种变体。M 的默认值是 10。In standard SQL, the syntax
DECIMAL( is
equivalent to
M)DECIMAL(.
Similarly, the syntax M,0)DECIMAL is equivalent
to DECIMAL(,
where the implementation is permitted to decide the value of
M,0)M. MySQL supports both of these
variant forms of DECIMAL syntax. The default
value of M is 10.
如果小数位数为 0,DECIMAL 的值不包含小数点或小数部分。If the scale is 0, DECIMAL values contain no
decimal point or fractional part.
DECIMAL 的最大位数是 65,但给定 DECIMAL 列的实际范围可能会受到该列的精度或小数位数的限制。当向这样的列分配一个小数点后位数超过指定小数位数的值时,该值将被转换为该小数位数。(具体行为取决于操作系统,但通常效果是截断到允许的位数。)The maximum number of digits for DECIMAL is
65, but the actual range for a given DECIMAL
column can be constrained by the precision or scale for a given
column. When such a column is assigned a value with more digits
following the decimal point than are permitted by the specified
scale, the value is converted to that scale. (The precise
behavior is operating system-specific, but generally the effect
is truncation to the permissible number of digits.)