浮点型(float 和 double)
MySQL数据类型 | 含义 |
float(m,d) | 单精度浮点型 8位精度(4字节) m总个数,d小数位 |
double(m,d) | 双精度浮点型 16位精度(8字节) m总个数,d小数位 |
注释:设一个字段定义为 float(5,3),如果插入一个数 123.45678,实际数据库里存的是 12.345,但总个数还以实际为准,即 5位.
定点数
浮点型在数据库中存放的是近似值,而定点类型在数据库中存放的是精确值。
decimal(m,d) 参数 m<65 是总个数,d<30 且 d<m 是小数位。
浮点数实例:
注释:float(M,D):M是精度,总位数;D标度,小数点后面的位数。
#创建t3数据库,数据类型为float(5,2)。
mysql> create table t3 ( salary float(5,2) );
Query OK, 0 rows affected (0.02 sec)
#测试插入"4444"报错,超出设定的数值范围.
mysql> insert into t3 values (4444);
ERROR 1264 (22003): Out of range value for column 'salary' at row 1
#插入"444.45"即插入成功.
mysql> insert into t3 values (444.45);
Query OK, 1 row affected (0.01 sec)
#查看表的数据.
mysql> select * from t3;
+--------+
| salary |
+--------+
| 444.45 |
+--------+
1 row in set (0.00 sec)
#查看数据结构.
mysql> desc t3;
+--------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+-------+
| salary | float(5,2) | YES | | NULL | |
+--------+------------+------+-----+---------+-------+
1 row in set (0.00 sec)
#float数据类型的最大存储值为-999.99.
mysql> insert into t3 values (-999.99);
Query OK, 1 row affected (0.02 sec)
mysql> select * from t3;
+---------+
| salary |
+---------+
| 444.45 |
| -999.99 |
+---------+
2 rows in set (0.00 sec)
浮点型与定点型的区别:
#创建表t4,测试浮点型列f和定点型列d的区别.
mysql> create table t4 (
-> f float(9,2),
-> d decimal(9,2)
-> );
Query OK, 0 rows affected (0.01 sec)
#两列插入相同的数据。
mysql> insert into t4 values (1234567.23,1234567.23);
Query OK, 1 row affected (0.00 sec)
#查看表中的数据.
mysql> select * from t4;
+------------+------------+
| f | d |
+------------+------------+
| 1234567.25 | 1234567.23 |
+------------+------------+
1 row in set (0.00 sec)
注释:float/double有精度损失,decimal定点型,更精确.
如果要插入的数据长度超过指定的M的长度,结果如何?
#表t3的float(5,2),插入"123.4567"。
mysql> insert into t3 values (123.4567);
Query OK, 1 row affected (0.01 sec)
#查看t3表的数据.
mysql> select * from t3;
+---------+
| salary |
+---------+
| 444.45 |
| -999.99 |
| 123.46 |
+---------+
3 rows in set (0.00 sec)
注意:"123.4567"表中的数据只有123.46,float/double有精度损失.