|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-05-02 12:12 UTC] cf0hay at gmail dot com
Description:
------------
var_export() truncates floating-point precision. serialize() does not have the same problem.
Test script:
---------------
<?php
$a = microtime(true);
echo "error of serialize(): ";
var_export($a - unserialize(serialize($a))); //This returns 0.
echo "\n";
echo "error of var_export(): ";
eval('$b = '.var_export($a,true).';');
var_export($a - $b); //Almost never 0.
echo "\n";
Expected result:
----------------
Exporting a floating-point value should generate enough digits to prevent precision loss. The script above should always return 0 on the second case.
Actual result:
--------------
The difference between the original floating point value and the one exported differs. The error is about 15 magnitude lower than the magnitude of the value itself.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 13:00:01 2025 UTC |
The difference came from var_export() ------------------------------------------------------- case IS_DOUBLE: tmp_len = spprintf(&tmp_str, 0,"%.*H", (int) EG(precision), Z_DVAL_PP(struc)); smart_str_appendl(buf, tmp_str, tmp_len); efree(tmp_str); break;------------------------------------------------------- serialize() ------------------------------------------------------- case IS_DOUBLE: { char *s; smart_str_appendl(buf, "d:", 2); s = (char *) safe_emalloc(PG(serialize_precision), 1, MAX_LENGTH_OF_DOUBLE + 1); php_gcvt(Z_DVAL_P(struc), PG(serialize_precision), '.', 'E', s); smart_str_appends(buf, s); smart_str_appendc(buf, ';'); efree(s); return; } ------------------------------------------------------- var_export() uses precision=14 while serialize() uses precision=17 by default. ------- [yohgaki@dev php-5.5]$ php -e precision=17 scr.php error of serialize(): 0 error of var_export(): 0 ------- Since var_export() is better to behave like serialize(), var_export() is better to use PG(serialize_precision) instead of PG(precision).