Search code examples
mysqlnanieee-754infinity

MySql IEEE floating point NaN, PositiveInfinity, NegativeInfinity


I have looked at many questions regarding this problem, but I have not found a solution. Hopefully this is not a duplicate question.

Problem

If I do any of:

INSERT INTO `Numbers`(`Number`) VALUES ('NaN')
INSERT INTO `Numbers`(`Number`) VALUES ('Inf')
INSERT INTO `Numbers`(`Number`) VALUES ('+Inf')

I get 0.0 inserted in the table. Sometimes I get:

Error Code: 1265. Data truncated for column 'Number'

I have also tried different casing and spelling, all with the same effect.

I have even tried:

INSERT INTO `Numbers`(`Number`) VALUES ('1111111111111000000000000000000000000000000000000000000000000000')

How do I insert a NaN floating point number into a MySql table?

If it really isn't possible then what is the reasoning? (Maybe I am using the incorrect version of MySql?)

Using NULL as NaN

The tables where I am actually using this I don't want to allow NULL values in those columns. So I don't like the idea of replacing NaN with NULL somewhere in the ORM layer


Solution

  • To get an overall idea of how MySQL manipulates numbers you can read the following chapters:

    The last article mentions this:

    The server includes dtoa, a conversion library that provides the basis for improved conversion between string or DECIMAL values and approximate-value (FLOAT/DOUBLE) numbers

    [...]

    The dtoa library provides conversions with the following properties. D represents a value with a DECIMAL or string representation, and F represents a floating-point number in native binary (IEEE) format.

    [...]

    conversions are lossless unless F is -inf, +inf, or NaN. The latter values are not supported because the SQL standard defines them as invalid values for FLOAT or DOUBLE.

    In short:

    • The SQL standard explicitly bans those values
    • MySQL complies with the standard in that aspect