经过排查,php中的 json_encode 函数,会对编码内容中的浮点数产生影响
具体验证如下:
$val = 0.288000000 * 100;
$arr = [
"key1" => "asdasdasda",
"key2" => $val
];
var_dump(json_encode($arr));
结果如下:
{"key1":"asdasdasda","key2":28.799999999999997}
如果要直接避免此问题,建议使用最简单的方案(即让变量被编码时被认为不是浮点数):
$val = 0.288000000 * 100;
$arr = [
"key1" => "asdasdasda",
"key2" => (string)$val
];
var_dump(json_encode($arr));
原创文章,作者:witersen,如若转载,请注明出处:https://www.witersen.com