對於小數的表示,mysql分爲浮點型和定點型兩種。浮點行爲FLOAT和DOUBLE,定點型只有DECIMAL。定點型在數據庫中以字符串的形式存放,所以更爲精確,通常表示貨幣等比較精確的數據。
他們均可以使用類型名稱後加(M,D)來表示,M表示一共顯式幾位數字,D表示表示小數位數,M和D又稱爲精度和標度。當DECIMAL沒有精度和標度是默認爲DECIMAL(10,0)。咱們建立表tDec,而且分別將字段id1,id2,id3字段設置爲FLOAT(5,2),DOUBLE(5,2),DECIMAL(5,2),分別插入值都爲爲1.34。mysql
mysql> create table tDec( -> id1 FLOAT(5,2), -> id2 DOUBLE(5,2), -> id3 DECIMAL(5,2) -> ); Query OK, 0 rows affected (0.20 sec) mysql> insert into tDec values(1.34,1.34,1.34); Query OK, 1 row affected (0.49 sec) mysql> select * from tDec; +------+------+------+ | id1 | id2 | id3 | +------+------+------+ | 1.34 | 1.34 | 1.34 | +------+------+------+ 1 row in set (0.00 sec)
咱們能夠發現數據正確的插入了數據表中。咱們再次插入數據,觀察插入後的結果:sql
mysql> insert into tDec values(1.344,1.344,1.344); Query OK, 1 row affected, 1 warning (0.01 sec) mysql> insert into tDec values(1.345,1.345,1.345); Query OK, 1 row affected, 1 warning (0.01 sec) mysql> insert into tDec values(1.3451,1.3451,1.3451); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> insert into tDec values(1.3411,1.3451,1.3461); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> insert into tDec values(1.3451,1.3450,1.3451); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> select * from tDec; +------+------+------+ | id1 | id2 | id3 | +------+------+------+ | 1.34 | 1.34 | 1.34 | | 1.34 | 1.34 | 1.34 | | 1.34 | 1.34 | 1.35 | | 1.35 | 1.35 | 1.35 | | 1.34 | 1.35 | 1.35 | | 1.35 | 1.34 | 1.35 | +------+------+------+ 6 rows in set (0.00 sec)
經過上面的結果咱們能夠看到,當一個字段被定義爲浮點型後,若是插入的精度超多該列定義的實際精度,則插入值會被四捨五入到實際定義的精度,而後插入,插入過程當中不會報錯。定點數在四捨五入插入的過程當中會給予警告,若是是在傳統模式下會報錯,沒法插入數據。浮點型在四捨五入的時候還會看決定是舍仍是入的那一位的下一位是否存在不存在(是否非0)則直接截斷,存在纔會四捨五入。咱們經過第三條和第四條和第六條數據做比較能夠獲得這個結論。數據庫
同時咱們不聲明精度和標度,創建表tDec1,而且插入數據,顯示結果爲:code
mysql> create table tDec1( -> id1 FLOAT, -> id2 DOUBLE, -> id3 DECIMAL -> ); Query OK, 0 rows affected (0.02 sec) mysql> insert into tDec1 values(1.3,1.3,1.3); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> insert into tDec1 values(1.5,1.5,1.5); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> insert into tDec1 values(1.1,1.5,1.6); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> select * from tDec1; +------+------+------+ | id1 | id2 | id3 | +------+------+------+ | 1.3 | 1.3 | 1 | | 1.5 | 1.5 | 2 | | 1.1 | 1.5 | 2 | +------+------+------+ 3 rows in set (0.00 sec)
當都不生聲明M和D時,FLOAT和DOUBLE會按實際值插入,DECIMAL默認爲DECIMAL(10,0),按四捨五入方式插入。字符串
下面咱們再看一個關於浮點數和定點數的精確度問題。table
mysql> create table tDec2( -> id1 FLOAT(10,2), -> id2 DECIMAL(10,2) -> ); Query OK, 0 rows affected (0.07 sec) mysql> insert into tDec2 values(131072.32,131072.32); Query OK, 1 row affected (0.00 sec) mysql> select * from tDec2; +-----------+-----------+ | id1 | id2 | +-----------+-----------+ | 131072.31 | 131072.32 | +-----------+-----------+ 1 row in set (0.00 sec)
從上面的例子能夠看出再插入的時候浮點型的數產生了偏差,這個是浮點數特有的問題。由於對於精度要求比較高的應該使用DECIMAL定點數類型,而不是浮點數類型。class