Last active
July 17, 2025 15:23
-
-
Save coccoinomane/03a718b13d77ba808e9289a85407d908 to your computer and use it in GitHub Desktop.
Version of `json_encode` that avoids rounding issues with decimal numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: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:
For more details, see this Stack Overflow thread.