php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74407 number goes wrong when json_encode
Submitted: 2017-04-10 16:43 UTC Modified: 2017-04-11 13:56 UTC
From: martin dot leni83 at gmail dot com Assigned: cmb (profile)
Status: Not a bug Package: json (PECL)
PHP Version: 7.1.3 OS: Ubuntu
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: martin dot leni83 at gmail dot com
New email:
PHP Version: OS:

 

 [2017-04-10 16:43 UTC] martin dot leni83 at gmail dot com
Description:
------------
When you do this very basic math and json_encode the result, the number encoded is not the one expected. 
It turns back to the right value when decoded.

Test script:
---------------
$number = 0.95*3;
echo $number."\n";
echo $json = json_encode([$number])."\n";
echo $array = json_decode($json)[0];

Expected result:
----------------
2.85
[2.85]
2.85

Actual result:
--------------
2.85
[2.8499999999999996]
2.85

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-04-11 13:56 UTC] cmb@php.net
-Status: Open +Status: Not a bug -Assigned To: +Assigned To: cmb
 [2017-04-11 13:56 UTC] cmb@php.net
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/

Thank you for your interest in PHP.

Note that this very issue is particularly related to[1]:

| serialize_precision is used instead of precision when encoding
| double values.

[1] <http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-changelog>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 12:01:31 2024 UTC