关于MySQL使用Float存储时的精度问题
官方文檔
https://dev.mysql.com/doc/refman/8.0/en/floating-point-types.html
官方文檔是這么說的:
11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE
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.
For FLOAT, the SQL standard permits an optional specification of the precision (but not the range of the exponent) in bits following the keyword FLOAT in parentheses; ; that is, FLOAT(p). MySQL also supports this optional precision specification, but the precision value in FLOAT(p) is used only to determine storage size. A precision from 0 to 23 results in a 4-byte single-precision FLOAT column. 翻譯:精度從0到23的結(jié)果是一個4字節(jié)的單精度浮點列。(也就是說,即使你把類型定義為float(16,2),也不可能達到16位的精度,因為float是用32bit存儲的,只能保證6~7位精度。) A precision from 24 to 53 results in an 8-byte double-precision DOUBLE column.
MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. For example, a column defined as FLOAT(7,4) will look like -999.9999 when displayed. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001.
As of MySQL 8.0.17, the nonstandard FLOAT(M,D) and DOUBLE(M,D) syntax is deprecated and support for it will be removed in a future MySQL version.
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, see Section B.4.4.8, “Problems with Floating-Point Values”
For maximum portability, code requiring storage of approximate numeric data values should use FLOAT or DOUBLE PRECISION with no specification of precision or number of digits.
翻譯
11.1.4浮點類型(近似值)-浮點,雙精度浮點
浮點和雙精度類型表示近似的數(shù)值數(shù)據(jù)值。MySQL為單精度值使用4個字節(jié),為雙精度值使用8個字節(jié)。
對于FLOAT, SQL標(biāo)準(zhǔn)允許在圓括號中的關(guān)鍵字FLOAT之后指定以位為單位的精度(但不允許指定指數(shù)的范圍);;也就是說,浮子§。MySQL也支持這個可選的精度規(guī)范,但是FLOAT§中的精度值只用于確定存儲大小。精度從0到23的結(jié)果是一個4字節(jié)的單精度浮點列。精度從24到53將產(chǎn)生一個8字節(jié)的雙精度雙列。
MySQL允許非標(biāo)準(zhǔn)語法:FLOAT(M,D)或REAL(M,D)或DOUBLE PRECISION(M,D)。在這里,(M,D)表示可以存儲最多M位的值,其中D位可能在小數(shù)點后面。例如,定義為FLOAT(7,4)的列在顯示時看起來像-999.9999。MySQL在存儲值時執(zhí)行四舍五入,所以如果您將999.00009插入到浮點數(shù)(7,4)列中,近似結(jié)果是999.0001。
從MySQL 8.0.17開始,不支持非標(biāo)準(zhǔn)的FLOAT(M,D)和DOUBLE(M,D)語法,在未來的MySQL版本中將不再支持它。
因為浮點值是近似的,而不是作為精確值存儲的,所以在比較中試圖將它們作為精確值處理可能會導(dǎo)致問題。它們還依賴于平臺或?qū)崿F(xiàn)。有關(guān)更多信息,請參見B.4.4.8節(jié),“浮點值的問題”
為了獲得最大的可移植性,需要存儲近似數(shù)值數(shù)據(jù)值的代碼應(yīng)該使用浮點或雙精度,而不指定精度或數(shù)字。
總結(jié)
以上是生活随笔為你收集整理的关于MySQL使用Float存储时的精度问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】求多个字符串的最长公共前
- 下一篇: MySQL索引机制:索引分类、索引的实现