Bug #75800 [Com]: json_encode produces unexpected results with summed floats
Edit report at https://bugs.php.net/bug.php?id=75800&edit=1
ID: 75800
Comment by: spam2 at rhsoft dot net
Reported by: yoch at yoch dot org
Summary: json_encode produces unexpected results with summed
floats
Status: Not a bug
Type: Bug
Package: JSON related
Operating System: Ubuntu 16.04.3 LTS
PHP Version: 7.2.1
Block user comment: N
Private report: N
New Comment:
and why "precision" defaults to 14 while serialize_precision defaults to -1
Previous Comments:
------------------------------------------------------------------------
[2018-01-11 15:05:23] requinix@php.net
We have a template response for that one too, actually:
Floating point values have a limited precision. Hence a value might
not have the same string representation after any processing. That also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.
If you would like to know more about "floats" and what IEEE
754 is, read this:
http://www.floating-point-gui.de/
-1 is "unlimited" precision, meaning that you can see the full float value - including
possible error introduced during math. The two json_encode() tests produce different results because
of the inconsis-- I mean, the magic of floating-point math.
To get the expected result in all cases you need a precision and serialize_precision of some value
between 3 and 16, such as 14.
2.4899999999999998
^ ^
3 16
------------------------------------------------------------------------
[2018-01-11 12:45:30] yoch at yoch dot org
Does that means that setting both "precision" and "serialize_precision" to
"-1" must produce the expected results? It does not right now.
------------------------------------------------------------------------
[2018-01-11 12:27:57] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to
report
a bug at http://bugs.php.net/how-to-report.php
http://php.net/manual/en/function.json-encode.php
> Changelog
> 7.1.0 serialize_precision is used instead of precision when encoding double values.
------------------------------------------------------------------------
[2018-01-11 11:50:03] yoch at yoch dot org
Description:
------------
With default php.ini settings (serialize_precision = "-1" and precision = "14"),
json_encode() produces inconsistent results.
After setting serialize_precision to "14" serialization working as expected.
Test script:
---------------
php -r 'echo 2.09 + 0.4;'
php -r 'echo json_encode(2.49);'
php -r 'echo json_encode(2.09 + 0.4);'
Expected result:
----------------
2.49
2.49
2.49
Actual result:
--------------
2.49
2.49
2.4899999999999998
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=75800&edit=1
Thread (7 messages)