Skip to content

Instantly share code, notes, and snippets.

@coccoinomane
Last active July 17, 2025 15:23
Show Gist options
  • Save coccoinomane/03a718b13d77ba808e9289a85407d908 to your computer and use it in GitHub Desktop.
Save coccoinomane/03a718b13d77ba808e9289a85407d908 to your computer and use it in GitHub Desktop.
Version of `json_encode` that avoids rounding issues with decimal numbers
/**
* Encode the given array to JSON, avoiding float values being arbitrarily
* added decimals.
*
* Credits to https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue
*/
function safe_json_encode($array, $flags = 0)
{
// Set the precision to the same value as the precision setting
// to avoid float values being arbitrarily added decimals.
$precision = ini_get('precision');
$originalSerializePrecision = ini_get('serialize_precision');
if ($originalSerializePrecision !== $precision) {
ini_set('serialize_precision', $precision);
}
// Encode the array to JSON
$json = json_encode($array, $flags);
// Restore the original serialize precision
if ($originalSerializePrecision !== ini_get('serialize_precision')) {
ini_set('serialize_precision', $originalSerializePrecision);
}
return $json;
}
@coccoinomane
Copy link
Author

coccoinomane commented Jul 17, 2025

Certain servers set the serialize_precision PHP setting wrongly: WHM, Local WP, etc. You have this problem if any of the following commands spits too many decimal digits:

php -r 'echo json_encode(0.7) . PHP_EOL;'
php -r 'echo json_encode(472.185) . PHP_EOL;'
php -r 'echo json_encode(array(472.185, round("45.99", 2))) . PHP_EOL;'

The function in the gist changes the PHP setting, spits out the correct json_encode, and finally restores the setting to the original value.

Test it with:

echo safe_json_encode(array(0.7, 472.185, round("45.99", 2)));

For more details, see this Stack Overflow thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment