php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75561 Json_encode does not encode numbers properly
Submitted: 2017-11-23 12:40 UTC Modified: 2017-11-23 15:28 UTC
From: anantaramdas at outlook dot com Assigned:
Status: Not a bug Package: JSON related
PHP Version: Irrelevant OS: Windows
Private report: No CVE-ID: None
 [2017-11-23 12:40 UTC] anantaramdas at outlook dot com
Description:
------------
I have PHP version 7.1.7






Test script:
---------------
$amount = 26000;
\Log::info("A: " . $amount);
$json = json_encode([
    'amount' => $amount,
]);
\Log::info("J: " . $json);

Expected result:
----------------
Expected Behavior
Gives following output:
info log [13:26:42] LOG.info: A: 26000
info log [13:26:42] LOG.info: J: {"amount":26000}

Actual result:
--------------
Gives following output:
info log [13:26:42] LOG.info: A: 26000
info log [13:26:42] LOG.info: J: {"amount":25999.999999999996}



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-11-23 15:17 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: Reproducible crash +Package: JSON related
 [2017-11-23 15:17 UTC] 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
> additionally the encoding of float values depends on the value of serialize_precision.

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/
 [2017-11-23 15:28 UTC] nikic@php.net
More specifically, you want to leave serialize_precision at the default value of -1. Not that your sample code could result in this problem in any case, but I assume that your 26000 is really the result of a floating-point computation those value is close to 26000.0.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Sun Dec 08 21:01:25 2019 UTC