php-serialize icon indicating copy to clipboard operation
php-serialize copied to clipboard

Invalid serialization for floating numbers

Open abhishek6262 opened this issue 3 years ago • 1 comments

There is a minor difference in the serialization done at the PHP and Javascript polyfill.

PHP will serialize 750.0 as d:750; Whereas, Javascript implementation for the same will serialize it as i:750;

This happens due to the internal working of Javascript and PHP. But is there a way, we can handle this? We have a very specific use case of generating an md5 hashed key from the serialized value but due to this minor difference, the hashed value is completely different for both PHP and Javascript.

abhishek6262 avatar Sep 13 '22 16:09 abhishek6262

Hello hello!

Thanks for checking back in. This is an interesting situation indeed. There's no quick and pretty way that comes to mind to solve this problem. One possible solution here would be to fake the depth / precision of the float, and then trim it out. For example, you could specify float precision in constructor, and try to serialize a float ie 750.000001 with precision of 1, so we could update this https://github.com/steelbrain/php-serialize/blob/1c75a879bf11757d4ae002ab35e4171864e5bd58/src/serialize.ts#L36 to take that precision into account and the trimmed value would be 750.0 in float.

What do you think?

steelbrain avatar Sep 13 '22 22:09 steelbrain