haskellieee-754zeroaeson

How do I distinguish negative zero with Aeson?


Haskell distinguishes negative zero:

ghci> (isNegativeZero (0 :: Float), isNegativeZero (-0 :: Float))
(False,True)

JSON also allows for distinguishing them, since both "0" and "-0" are valid, syntactically.

But Aeson throws away the sign bit:

ghci> isNegativeZero <$> eitherDecode "-0"
Right False

Why? How can I decode a JSON document while distinguishing non-negative and negative zero?


Solution

  • It looks like in Data.Aeson the floating point number is constructed using Data.Scientific.scientific

    scientific :: Integer -> Int -> Scientific
    

    scientific c e constructs a scientific number which corresponds to the Fractional number: fromInteger c * 10 ^^ e.

    Since the mantissa is an Integer, where we have 0 == -0, it can not construct a negative zero. Not the best API for constructing special floating point values, it seems.

    Perhaps you should file a bug for aeson, asking for a workaround in the parser.