MySQL 的 float 精度问题

结论:要求绝对精度且数据较大的时候,不要使用 MySQL 的 float 或者 double,使用 decimal

MySQL 中的默认 float 型占 4 字节,只能在值的二进制表示在 32 位以内的时候保证精度,超出就会被四舍五入,导致数据的不准确。double 型和 float 型原理上一样,只是占了 8 字节,所以可以保存 64 位。这两种类型原本不保证精确性。

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.

因此在要求绝对精度的时候,使用 decimal 型存储比较靠谱。

decimal(a,b)

  • a 指定指定小数点左边和右边可以存储的十进制数字的最大个数,最大精度 38。
  • b 指定小数点右边可以存储的十进制数字的最大个数。小数位数必须是从 0 到 a 之间的值。默认小数位数是 0。

电表项目数据存储遇到的问题,用 float 存的电能值莫名其妙就不精确了。

参考:MySQL如何选择float, double, decimal