mysql使用double的坑

  碰到一個很奇葩的問題,mysql默認是四捨五入的,但是,使用double,有時候不四捨五入。

犯罪現場還原

表結構

CREATE TABLE `test` (
  `salary_decimal` decimal(11,2) DEFAULT NULL,
  `salary_double` double(11,3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

表數據

  salary_decimal 和 salary_double 分別插入 -96.845

  很神奇的是,保存後,decimal的是 -96.85 ,double的是-96.84

  然而,把double的精度從2增加到3,mysql會自動從 -96.84 變爲 -96.845 差點亮瞎了我的眼睛

引發的問題

  這樣引發了兩個問題:

  1. 兩邊數據不一致,一個decimal是-96.85 一個double是-96.84
  2. sum函數,結果不準確。使用double的表,求和的時候,會出問題。sum(-96.84列+ -3.15)的結果不是 -99.99 而是 -100.00

結論

  1. 針對問題1,特意找了下資料,發現double本來就是不精準的

    附上官網的解釋

    For FLOAT, the SQL standard permits an optional specification of the precision (but not the range of the exponent) in bits following the keywordFLOAT in parentheses. MySQL also supports this optional precision specification, but the precision value is used only to determine storage size. A precision from 0 to 23 results in a 4-byte single-precision FLOAT column. A precision from 24 to 53 results in an 8-byte double-precision DOUBLEcolumn.

  2. 針對問題2,有了問題1的前提,sum的結果自然也是不精準

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章