当前位置: 首页 > 后端技术 > PHP

PHP7serialize_precision配置不当导致json_encode()浮点小数溢出错误

时间:2023-03-30 02:05:08 PHP

感谢@地狱之星:已经找到原因,此现象只出现在PHP7.1+版本,建议使用默认值serialize_precision=-1参考:https://wiki.php.net/rfc/预...---------------------------------------------------------------------------事情是这样的,在项目中发现一个奇怪的现象,json_encodea价格为浮点数的数据,会发生溢出,如:$depth)return$d;if(is_array($d)){foreach($das$i=>$v){$d[$i]=json_encode_pre($v,$depth,$level+1);}返回$d;}if(is_float($d)){#测试发现当number_format的有效个数小于18时(保守取16),不会溢出$p=16-strlen(intval($d));$f=number_format($d,$p);如果($p>1){$f=preg_replace('/0+$/','',$d);}返回$d;}return$d;}回声麻木er_format(277.2,14);//当处理18位有效数字时(277.2已经有4位有效数字)//277.199999999999989echonumber_format(277.2,12);//当16位时//277.2000000000000echojson_encode(json_encode_pre(277.2));//"277.2"看到这个结果,我猜是有效位数的问题导致了溢出。PHP怎么会有这么愚蠢的设计?这是我当时的想法。然后想着能不能从Startedwiththesourcecode获取,于是查看了php源码,发现了这段代码:staticinlinevoidphp_json_encode_double(smart_str*buf,doubled,intoptions)/*{{{*/{size_t长度;字符数[PHP_DOUBLE_MAX_LENGTH];php_gcvt(d,(int)PG(serialize_precision),'.','e',num);len=strlen(数);if(options&PHP_JSON_PRESERVE_ZERO_FRACTION&&strchr(num,'.')==NULL&&len