PHP’s serialize_precision hidden danger

The PHP configuration directive serialize_precision can cause hard to debug issues.

When deviated from its default value, it can lead to inexpected behavior in common functions like json_encode() and serialize().

The Problem

If you change the serialize_precision setting from its default value of -1, the float precision will be more digits than 2 decimal places.
If you are not aware of this setting, it can lead to hard-to-debug issues in your application.

This behavior can silently break payload validation, API responses, or any logic that relies on exact string comparisons of numeric values or which assumes that float values come with 2 decimal places.

Impact on Functions

When serialize_precision is set to something other than -1, the following functions are affected:

  • json_encode()
  • json_decode()
  • serialize()
  • unserialize()

Consider the following example.
Setting a high precision changes the number in the JSON output:

<?php
// High precision
ini_set("serialize_precision", 100);
echo json_encode(12.12);
// Output: 12.1199999999999992184029906638897955417633056640625

// Default (recommended) precision
ini_set("serialize_precision", -1);
echo json_encode(12.12);
// Output: 12.12Code language: HTML, XML (xml)

How to Check Your Configuration

So better verify your current setting, especially when dealing with mysterious floating-point issues in legacy environments.
When on shared hosting, you might even not know that the setting was changed.

You can check it via code:

echo ini_get("serialize_precision");Code language: PHP (php)

Or, if you are using PHP 8.5 or newer, you can conveniently check for configuration differences using the CLI:

php --ini=diff

This will highlight any settings that differ from the PHP defaults, making it much easier to spot such dangerous configurations.

Conclusion

If you encounter unexpected floating-point behavior in your PHP application, check the serialize_precision setting first. It’s a simple fix that can save you hours of debugging.