加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

用于number的PHP serialize()输出是打击的

发布时间:2020-12-13 17:08:01 所属栏目:PHP教程 来源:网络整理
导读:我正在计算 PHP中文件上传的大小,格式为MB,带有一个小数位,如下所示: $metadata['upload_data'] = intval($_FILES['Filedata']['size'] / 104857.6) / 10; 当我回显$metadata [‘upload_data’]时,输出为1.7,正如我所料.但是当我使用serialize($metadata)序
我正在计算 PHP中文件上传的大小,格式为MB,带有一个小数位,如下所示:

$metadata['upload_data'] = intval($_FILES['Filedata']['size'] / 104857.6) / 10;

当我回显$metadata [‘upload_data’]时,输出为1.7,正如我所料.但是当我使用serialize($metadata)序列化数组并将其保存到文件时,输出为:

a:2:{s:7:"uploads";i:11;s:11:"upload_data";d:1.6999999999999999555910790149937383830547332763671875;}

我试图通过以MB为单位存储文件大小而不是字节来提高效率,但这看起来更糟糕!为什么PHP会以这种方式存储它?我是以正确的方式来做这件事的吗?谢谢

解决方法

从手册: http://php.net/manual/en/language.types.float.php

Additionally,rational numbers that
are exactly representable as floating
point numbers in base 10,like 0.1 or
0.7,do not have an exact representation as floating point
numbers in base 2,which is used
internally,no matter the size of the
mantissa. Hence,they cannot be
converted into their internal binary
counterparts without a small loss of
precision. This can lead to confusing
results: for example,
floor((0.1+0.7)*10) will usually
return 7 instead of the expected 8,
since the internal representation will
be something like
7.9999999999999991118….

如果你想在你的数组的序列化版本中看到“1.7”,我建议使用json_encode和json_decode.这些函数最终比序列化和反序列化更快,也更容易阅读(通过更容易阅读,我的意思是一个人阅读它们,而不是机器).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读