json_encode adding lots of decimal digits

Why is this happening? Can I prevent this? (besides passing them as string)

var_dump(json_encode([1002.31, 2002.42]));


string(39) "[1002.3099999999999,2002.4200000000001]"


You should configure ‘precision‘ and ‘serialize_precision’ params

precision = 14
serialize_precision = -1

Test case:

php -r 'var_dump(json_encode([1002.31, 2002.42]));'
string(39) "[1002.3099999999999,2002.4200000000001]"

php -r 'ini_set("precision", 14); ini_set("serialize_precision", -1); var_dump(json_encode([1002.31, 2002.42]));'
string(17) "[1002.31,2002.42]"

Quick Solution:

Add this to the top of code. to stop this behavior.


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top