您现在的位置是:首页 > 学无止境
配置不当导致json_encode浮点小数溢出错误
PHP7 serialize_precision 配置不当导致 json_encode() 浮点小数溢出错误
<?phpecho json_encode(277.2);// 输出结果为: 277.199999999999989
function json_encode_pre($d, $depth=128, $level=0){if($level>$depth) return $d;if(is_array($d)){foreach ($d as $i => $v) { $d[$i] = json_encode_pre($v, $depth, $level+1); }return $d;}if(is_float($d)){# 测试发现number_format有效数字低于18(保守取16)时,不会溢出$p = 16 - strlen(intval($d));$f = number_format($d, $p);if($p>1){ $f = preg_replace('/0+$/','', $d); }return $d;}return $d;}echo number_format(277.2, 14); // 当18位有效数字处理(277.2已有4位有效数字)// 277.199999999999989echo number_format(277.2, 12); // 当16位// 277.2000000000000echo json_encode(json_encode_pre(277.2));// "277.2"
static inline void php_json_encode_double(smart_str *buf, double d, int options) /* {{{ */{size_t len;char num[PHP_DOUBLE_MAX_LENGTH];php_gcvt(d, (int)PG(serialize_precision), '.', 'e', num);len = strlen(num);if (options & PHP_JSON_PRESERVE_ZERO_FRACTION && strchr(num, '.') == NULL && len < PHP_DOUBLE_MAX_LENGTH - 2) {num[len++] = '.';num[len++] = '0';num[len] = '\0';}smart_str_appendl(buf, num, len);}
<?phpecho json_encode(277.2);// 输出结果为: 277.2
; php.ini; When floats & doubles are serialized store serialize_precision significant; digits after the floating point. The default value ensures that when floats; are decoded with unserialize, the data will remain the same.serialize_precision = 16; The number of significant digits displayed in floating point numbers.; http://php.net/precisionprecision = 16
<?phpecho json_encode(277.0);// 277echo json_encode(277.0, JSON_PRESERVE_ZERO_FRACTION);// 277.0
上一篇:面试官问如何优化慢 SQL ?
文章评论
- 登录后评论
点击排行
-
php-fpm安装、配置与优化
转载自:https://www.zybuluo.com/phper/note/89081 1、php中...
-
centos下postgresql的安装与配置
一、安装(以root身份进行)1、检出最新的postgresql的yum配置从ht...
-
Mysql的大小写敏感性
MYSQL在默认的情况下查询是不区分大小写的,例如:CREATE TABLE...
-
关于URL编码
转载自:http://www.ruanyifeng.com/blog/2010/02/url_encoding....
-
header中的Cache-control
网页的缓存是由HTTP消息头中的“Cache-control”来控制的,常见的...