Why does MySQL round floats way more than expected?

前端 未结 2 1827
南旧
南旧 2021-02-07 11:33
UPDATE some_table SET some_float_field=1919.987 WHERE id=123

SELECT * FROM some_table WHERE id=123

where some_float_field is a field defined as \"floa

2条回答
  •  走了就别回头了
    2021-02-07 11:58

    from the manual of FLOAT:

    The FLOAT and DOUBLE types represent approximate numeric data values. MySQL uses four bytes for single-precision values ..

    The emphasis here lies on approximate. If you need to store exact values, you should really use the DECIMAL data type.

    For FLOAT, MySQL uses the IEEE standard 754 for binary floating point arithmetic to "compress" any fraction of a number into 4 bytes (or 8, for DOUBLE).

    Note that this is applied to any value, regardless if the value (decimal part and fraction) could be precisely represented in 4 bytes! For example, the representation of 0.01 in floating point is exactly 0.009999999776482582092285156250 - even though 0.01 would perfectly fit in 32-bits of memory using another storage format.

    Wikipedia explains the concept of floating point pretty well.

    Note that the algorithm is affected by the precision specified in the column definition.
    See this SQL fiddle example.

提交回复
热议问题