ArduinoJson icon indicating copy to clipboard operation
ArduinoJson copied to clipboard

1.7976931348623147e308 is serialized to 1.797693135e308, which is out of double's range

Open bblanchon opened this issue 4 years ago • 1 comments

StaticJsonDocument<300> doc;
doc.set(1.7976931348623147e+308);
serializeJson(doc, std::cout); // 1.797693135e308

Online demo: https://wandbox.org/permlink/sJfBXevl6vd3KDL5

The rounding is correct, but the value is out of double's range. This can be an issue because when we deserialize the document, we get inf.

One way to mitigate this issue would be to reduce the value before stringification, like so:

// prevent rounding out of double's range
if (value > 1.797693134e308) 
  value = 1.797693134e308

Another option would be to add some slack in the deserialization code so that it returns 1.7976931348623147e+308 instead of inf.

I'm not sure if this issue classifies itself as a bug since the workaround can be considered a bug as well.

bblanchon avatar Mar 03 '21 14:03 bblanchon

Hey! Would it not be possible to store the number as a string data type? That way you can preserve each digit during the serialization and deserialization process. An alternative would be to use a long double data type (12 bytes) to store the number with precision. The issue is that using this method is not as reliable because the compiler and platform used can still lead to overflow. Try also installing and using the GNU Multiple Precision Arithmetic Library if possible - #include <gmp.h>.

hariskhawja avatar Aug 02 '23 22:08 hariskhawja