国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > 文庫 > 正文

Double類型精度問題造成的錯誤

2024-09-07 22:12:34
字體:
來源:轉載
供稿:網友
       研發同事讓把某個double類型字段的值四舍五入保留2位小數,mysql中round(col,2)可以實現四舍五入并且保留2位小數,但是神奇的事情發生了:發現有的四舍五入是正確的,而有的不是我們想要的結果,如下:簡單模擬此場景:
 
      yujx>drop table dd;
      yujx>create table dd (a double);
      yujx>insert into dd values(956.745),(231.34243252),(321.43534),(5464.446);
      yujx>select a,round(a,2) from dd;
+--------------+------------+
| a            | round(a,2) |
+--------------+------------+
|      956.745 |     956.74 |    #可以看到并不是我們期望的956.75
| 231.34243252 |     231.34 |
|    321.43534 |     321.44 |
|     5464.446 |    5464.45 |
+--------------+------------+
4 rows in set (0.00 sec)
 
The FLOAT and DOUBLE types represent approximate numeric data values. MySQL uses four bytes for single-precision values and eight bytes for double-precision values.
 
Because floating-point values are approximate and not stored as exact values, attempts to treat them as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies. For more information, seeSection B.5.5.8, “Problems with Floating-Point Values
 
“Problems with Floating-Point Values”
B.5.4.8 Problems with Floating-Point Values
 
Floating-point numbers sometimes cause confusion because they are approximate and not stored as exact values. A floating-point value as written in an SQL statement may not be the same as the value represented internally. Attempts to treat floating-point values as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies. The FLOAT and DOUBLE data types are subject to these issues. For DECIMALcolumns, MySQL performs operations with a precision of 65 decimal digits, which should solve most common inaccuracy problems.
 
由于浮點數存儲的是近似值而不是確切的值,某些時候可能導致混亂。一個浮點數值在SQL語句作為內部表示的值可能不同。試圖使用float、double來存儲確切的值可能會出現問題,他們也依賴不同平臺和實現方式。而對應DECIMAL類型,MySQL作為65位精度進行操作,可以解決此類精度問題。
  
綜上,如果想精確的存儲浮點數值,應該使用DECIMAL.比如金額等。
 
DECIMAL, NUMERIC
11.2.2 Fixed-Point Types (Exact Value) - 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。
 
DECIMAL和NUMBERIC存儲的是確切的數值,使用它們可以保證精確度,例如用于存儲金額數據。在MySQL中,NUMBERIC和DECIMAL以同樣的類型實現。

(編輯:武林網)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 福贡县| 沂水县| 通河县| 嘉峪关市| 鸡东县| 凤冈县| 嘉荫县| 祥云县| 岚皋县| 通河县| 盘锦市| 长葛市| 庆云县| 武川县| 清流县| 沂水县| 澎湖县| 仪陇县| 尤溪县| 天等县| 大理市| 五大连池市| 仲巴县| 九江县| 毕节市| 玛纳斯县| 隆昌县| 景泰县| 汝州市| 四会市| 大竹县| 洛隆县| 砚山县| 绿春县| 泗洪县| 金阳县| 来宾市| 平乡县| 会昌县| 麻栗坡县| 元朗区|