为什么会这样呢?我可以防止这种情况吗? (除了将它们作为字符串传递外)

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

输出:
string(39) "[1002.3099999999999,2002.4200000000001]"

最佳答案

您应该配置'precision'和'serialize_precision'参数。

precision = 14
serialize_precision = -1

测试用例:
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]"

10-04 13:19