[1.7.x] Fixed #23770 -- Changed serialization strategy for floats with respect to NaN and Inf

Thanks to w0rp for the report

Backport of c7c098cf97fbb1416f302c76799058ad63a5f7aa from master.